ASP.NET MVC Model Binding

Beginner

2019-04-10

MVC Model Binding

MVC Model Binding is the process of mapping incoming HTTP requests to key-value pairs and use those pairs to populate the model class object according to the attribute name.

It’s the opposite to HTML Helpers that we used earlier to generate HTML tags corresponding to C# classes.

 

What is MVC Model Binding

MVC Model Binding is converting HTTP request values (from query string or form collection) to action method parameters. these parameters can be primitive types or complex types.

In traditional action method, HTTP request values could be accessed from Request.QueryString and Request (Request.Form) object to get the value from HttpGet and HttpPOST request.

for example, to access a GET method parameters we need to access it through Request.QueryString

int id = (int) Request.QueryString[“userID”];

and to access a POST method parameters we needed to access it through Request object

int id = (int) Request[“userID”];

 

Accessing values through those two methods can be time consuming and you need to do the right type of parsing to be able to manipulate the data.

MVC Model Binding Types

MVC Binding Types can be either:

  • Primitive Type Binding
  • Complex Type Binding

Binding to a primitive type

HTTP request embeds data into QueryString. MVC automatically binds the data to their respective action parameters.

Binding is case-sensitive

MVC-Model-Primitive-Binding

Binding to a complex type

Binding also works for complex types ASP.NET MVC automatically creates an object from the complex type and populates the properties from the HTTP request type values.

MVC-model-complex-binding

we will modify the contact us example we developed in the previous tutorial to use complex model binding.

 

MVC Model Binding Example

In the previous tutorial : ASP.NET MVC Contact Us Data-Entry Application We created a contact us form and parsed its content to the Home controller through [HttpPost] attributed.

User could enter his name, email and message. Then we parse the name to the view saying thanks to the user.

In this tutorials we will use MVC Model binding and data validation to enhance the data entry process.

You can see the second overloaded ContactUs() method from the previous tutorial accepts a contactMessage model. how the conversion is done between HTML Forms and C# classes ? It’s MVC model binding.

Modify the second ContactUs method to parse the model to the view


Let’s improve our contact us page . Modify the ContactMessage class to be like :


Recreate the view for the :


as we did in the previous tutorial by right clicking inside it’s body . choose Add view . choose the view model to create and choose ContactMessage. click Add.

The generated ContactUs.cshtml output will be :


the added section is an input checkbox for the newly added IsSatisfied Boolean field.

Run the project and navigate to the contact us field, you can see the checkbox is rendered .

MVC-Model-Binding

Modify the Thanks.cshtml page so that we can use the IsSatisfied field we just added.


The “Model”  property contains the parsed model. it will have access to all the ContactMessage class. Here we are checking to see if the user is happy with the service or not, with each case we will show a different message

In case the user not satisfied :

MVC-Model-Binding-1

MVC-Model-Binding-2

In case the user is happy :

MVC-Model-Binding-3

MVC-Model-Binding-4

Data Validation

So far we haven’t validated any input from the user.

for example : we didn’t check whether he entered a valid email or not. We didn’t check if the user entered all the required fields or not.

ASP.NET MVC uses an approach called Code first, that’s what we have used. we designed a our model using code classes. then if we wanted we could generate database using those classes.

model classes uses Data annotation to specify how the model data behaves. for example we can specify the property type, whether it’s required or not and what is the error message to be displayed if those properties couldn’t be matched.

modify the ContactMessage Class to be like :


the “Required” attributes specifies that the field is required. and if the user didn’t fill the field the “ErrorMessage” variable value will be displayed.

the “DataType” attribute species the attribute type to be able t against its format for example to check if an email is valid or not.

 

Modify the ContactUs method inside HomeController to be like :


here we are checking if the Model contains any error then it should re-render the view showing the error messages. otherwise we will proceed to render the “Thanks” view.

Modify the ContactUs.cshtml form code to be able to display the validation error messages.


now try submitting the form without entering the required fields. you can see the error messages we have specified are shown.

MVC-Data-validation

Resources

1- Model Binding

Summary

In this tutorial we explained how to do model binding between the view and controller.

To check the model state. we used data annotation do data validation inside the model class and displayed custom error messages.

In the next tutorial we will understand how to change the styling of our form page.

We will see how to import external CSS stylesheet. Stay Tuned.