MVC: Accessing Form Values

Please see my other MVC articles.

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 ().

1-MVC-4-Accessing-Form-Values

2-MVC-4-Accessing-Form-Values

3-MVC-4-Accessing-Form-Values

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.

4-MVC-4-Accessing-Form-Values

When my test form loads, I will update the fields and press the UpdateTestRecord link.

5-MVC-4-Accessing-Form-Values

The first few lines find my record which is viewable in a watch window.

6-MVC-4-Accessing-Form-Values

As each form value is retrieved, the corresponding model attribute is updated.

7-MVC-4-Accessing-Form-Values

Finally, the database is updated with the command db.SaveChanges().

8-MVC-4-Accessing-Form-Values

Leave a comment