When you create a new Controller class on a ASP.NET MVC VS Project (right-clicking over folder "Controllers", then Add, then Controller), a dialog box lets you choose VS to autogenerate methods for Create, Update, Delete and Details scenarios.
When you do so, two methods are generated for each of these scenarios, for example:
//
// GET: /Address/Create
public ActionResult Create(int customerId) {...}
//
// POST: /Address/Create
[HttpPost]
public ActionResult Create(int customerId, FormCollection collection) {...}
And this can be confusing. One could think that only one function is necessary to "create" a "customer" (this is the example).
To understand why does VS generate two methods, we only have to add a breakpoint on each one of them and see when are they called:
The first one, the GET one, is called when the user clicks on the link that sais "create new customer" on the web page.
This "click" (the "get" method) should display a new page with the text boxes needed to fill in all the fields that a customer needs (name, company, address, and so on, whatever).
This page has an "OK" button at the bottom.
Only when this button is pressed the new customer will be really created and added to the database.
Well: This button is what triggers the second function, the "POST" one.
So this "post" method (the OK button) should insert the new customer into the database and then return back to the initial page or whatever.
So, you see that we need to call two functions in order to accomplish the creation, and each one of them is needed and have a very different aim.
You do not always need this double-step approach:
To delete a customer, for example, you will probably need to use only one function, the "get" method should be enough: You click on a "delete" link, then the function triggered should delete the item from the database and then return the same page. No need to have a form, to fill in fields...
In short:
The two-steps approach of the MVC Controller is intended for this:
- the MVC Controller GET method (click "create") returns the form page, with the input boxes, etc.
- then the MVC Controller POST method (click "OK") creates the new instance of the entity with the data that the form has, then inserts it into the database, and finally returns to the previous page.
I hope this helps!
Kind regards,
Ricardo.
Rjain8, if this helps please login to Mark As Answer. | Alert Moderator