Leveraging the FormCollection object to retrieve user input.
Collecting user input is one of the most common deliverables in Internet applications for which MVC provides a robust mechanism called the FormCollection.
Beginning where my MVC 4 ADO.NET Entity Data Model article ended, I will demonstrate how to leverage FormCollection to collect user input.
First, I’ll create a new View which houses my form and exposes my TestModel supporting the fields provided to the user for input.
The first line exposes my TestModel.
The Html form targets my UpdateTestRecord action within the Test controller. This line also signals to the view a Post action will be invoke instead of the usual Get Http verb.
Finally, notice the Html form uses the Post HttpVerb to send the form’s contents to the Controller Action UpdateTestRecord ().
With my Model’s attributes exposed to the Html form’s Post Action, now I will provide the controller which loads my test record to update from the user’s input and Model for processing.
When my test form loads, I will update the fields and press the UpdateTestRecord link.
The first few lines find my record which is viewable in a watch window.
As each form value is retrieved, the corresponding model attribute is updated.
Finally, the database is updated with the command db.SaveChanges().