Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: what code gets called when you click the "submit" button?

MVC newbie question; I'm learning by playing around rather than Reading The Manual... :)

I see when I create an "Edit" view that the auto-generated view includes a "submit" button:

<input type="submit" value="Save" />

But what code gets called behind the scenes to do this save? Specifically, the model underlying this view has its own fancy save logic in code that I would want to call. How do I get the view to invoke my code instead of whatever standard code is being called invisibly behind the scenes?

like image 667
Shaul Behr Avatar asked Apr 11 '11 12:04

Shaul Behr


2 Answers

It's not the button that defines what happens, but the form itself. The button of type submit (one per form) just triggers the form submission, which is handled by the form itself.

A form has an action - e.g.:

<form name="input" action="users/save" method="post">
    <!-- Form content goes here -->
    <input type="submit" value="Submit" />
</form>

The action is an URL and what happens is that the browser collects the values of all the fields in the form (<input...>) and posts them to the specified url.

In ASP.NET MVC forms are usually defined using the Html helpers, so that building the URL for the form action is delegated to ASP.NET MVC. For the above for example:

<% using(Html.BeginForm("Save", "Users")) %>
<% { %>
    <!-- Form content goes here -->
    <input type="submit" value="Save" />
<% } %>

Which in this case will create a url /users/save and the form will post to that url. That in terms will trigger the ASP.NET routing which will handle the /users/save url and break it into chunks so that it knows that it has to invoke the "Save" action method on the "Users" controller class. It will then read all the incoming field name-value pairs and try to map them to the method parameter names if any.

like image 60
Ivan Zlatev Avatar answered Nov 15 '22 15:11

Ivan Zlatev


It would call whatever public action method the form action is pointing to on your controller. You can then call save on the view model.

    public virtual ActionResult Save(MyViewModel model) {
        model.Save();            

        --- more code to do stuff here
    }

Set your form action to MyController/Save

You can also use using (Html.BeginForm... in your code to point the form to a specific action method on a specific controller.

like image 45
Chris Kooken Avatar answered Nov 15 '22 13:11

Chris Kooken