Introduction To ASP.NET MVC Model Binding

ASP.NET MVC model binder allows you to map Http Request data with the model. Http Request data means when a user makes a request with form data from the browser to a Controller, at that time, Model binder works as a middleman to map the incoming HTTP request with Controller action method.

What you will learn
  • Basic understating of a Model Binder.
  • Http request mapping using form collection and drawbacks of form collection
  • Model Binder with class type 
  • Model Binder with Update Model
Target Audience
  • Basic level programmer.
  • All ASP.NET/C# developers who want to learn MVC using C# concept.
ASP.NET MVC Model Binder's Graphical flow

As we know once a user makes the HTTP request with form data, the request will redirect to the respective Controller Action method and Model. Once the request reaches the controller, the model binder will map the request with respective action method.

Basically, Model binder gives the option to map the http request with respective Controller’s action method and Model. It works like a middleman between View and Controller and Model.
ASP.NET
Fig: Model Binder

ASP.net MVC provides various options to map the http request (browser request or form data) /view’s data to model properties via controller action method.

  1. Form Collection
  2. Model binding
Http request mapping using FormCollection in Asp.net mvc

FormCollection

The main objective of FormCollection class capture the  form’s input values  and  map with the respective controller’s action method & model’s data field

Let we see practical approach how form’s data will map using Form Collection class.

Step1

Open the VS 2013 and select the  ASP.NET web application.

ASP.NET

And select the MVC template with individual User account.

ASP.NET

Let add the home controller with index action method.

Step 1

  1. public ActionResult Index()  
  2. {  
  3.     return View();  
  4. }  
  5. /*Form data submission with simple type binding*/  
  6. [HttpPost]  
  7. public ActionResult Index(int Emp_Id, string Emp_Name, String Emp_Add)  
  8. {  
  9.   
  10.     ViewBag.SucessMessage = "Employee Info save" + Emp_Id;  
  11.     return View();  
  12.   
  13. }  

Step 2

Creating the view

  1. @{  
  2.     ViewBag.Title = "Home Page";  
  3. }  
  4.   
  5. <div class="jumbotron">  
  6.     <strong>ASP.NET MVC</strong>  
  7. </div>  
  8.   
  9. <tr class="form-group">  
  10.     @using (Html.BeginForm())  
  11.     {  
  12.         <table align="center">  
  13.             <tr >  
  14.                 <td align="center">  
  15.                     @Html.Label("EmployeeID:")  
  16.                     @Html.TextBox("Emp_Id")  
  17.                 </td>  
  18.             </tr>  
  19.   
  20.             <tr>  
  21.                 <td align="center">  
  22.                     @Html.Label("EmployeeName:")  
  23.                     @Html.TextBox("Emp_Name")  
  24.                 </td>  
  25.             </tr>  
  26.             <tr>  
  27.                 <td align="center">  
  28.                     @Html.Label("EmployeeAdd:")  
  29.                     @Html.TextBox("Emp_Add")  
  30.                 </td>  
  31.             </tr>  
  32.   
  33.             <tr>  
  34.                 <td align="center">  
  35.                     <input type="submit" value="Submit" class="btn-primary" />  
  36.                 </td>  
  37.   
  38.             </tr>  
  39.             <tr>  
  40.                 <td>  
  41.   
  42.                     @ViewBag.SucessMessage  
  43.                 </td>  
  44.             </tr>  
  45.   
  46.         </table>  
  47.   
  48.     }  

Step3

Now our code is ready for run .press f5 and sees the output.

ASP.NET
Now let understand the code flow. Once we enter the input values and submit the data, form collection will capture these input values and hit the respective controller action method.

For better understanding I have put the debugger breakpoint   in post Index action method .

ASP.NET
Ones we click on the submit button control will go to Post Index action method with the captured form’s data.


ASP.NET

Now we can see that Form Collection captures the form’s data value.

Cons of form collection:

  1. It’s not suitable if our number of input field increases
  2. In form collection data mapping approach, we need to do extra type casting work. As we see in the above example, before assigning the value into respective data variable we need to do type casting. 

So to overcome these scenarios ASP.net MVC provides the model binder concept.

Http request mapping using  ASP.net MVC model Binder with class type
 
In Model binder we need to create the Model class with required data field and after that we  can pass this Model class’s object  into  controller’s action method for  data mapping.

Let’s understand the above statement with practical example.

Step1

Create the Model Class with name EmployeeModel. Go to Model’s folder and add the model class like below snapshot.

ASP.NET

Step 2

Model class(EmployeeModel) add the required filed. 

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. namespace MVC_ModelBinding.Models    
  6. {    
  7.     public class EmployeeModel    
  8.     {    
  9.         public int Emp_Id { getset; }    
  10.         public string Emp_Name { getset; }    
  11.         public string  Emp_Add { getset; }   
  12.     }    
  13. } 

Step 3

Now we need to add the reference of this model in to Controller with help of using statement. Now we need to pass the  EmployeeModel's object  as parameter into Index  Action method, so that  our form’s data/http request data will be map, below is the code

  1. [Httppost]     
  2. public ActionResult Index(EmployeeModel obj)    
  3. {  
  4.     ViewBag.SucessMessage = "Employee Info save" +"-" + obj.Emp_Id;    
  5.     return View();   
  6. } 

Note

ASP.net MVC uses the System.Web.MVC.DeafulBinder.

Let put the debugger and see the capture values.

ASP.NET
Click the submit button.

ASP.NET

Now we can see the model binder capture value, which will map into our Employee Model’s class field.

ASP.net MVC Model Binder with UpdateModel function

UpdateModel() function observe the all  form’s input value/HttpRequest and updates into the model class.

Note

In Update Model concept instead of passing the Model class’s object   as parameter in Action method, we will pass the Model class’s object   as parameter in UpdateModel ()

Let understand with example, 

  1. [HttpPost]    
  2. /* Binding With Update model*/    
  3. public ActionResult Index()    
  4. {    
  5.     if (ModelState.IsValid)    
  6.     {    
  7.         EmployeeModel obj=new EmployeeModel();    
  8.         UpdateModel(obj);    
  9.         ViewBag.SucessMessage = "Employee Info save" + "-" + obj.Emp_Id;    
  10.         return View();    
  11.     }    
  12.     return View();  
  13. } 

Now once we compile this code we will get the below compile time error (same name index method). To remove this error we need to use the Action Name attribute.

Action Name attribute is responsible for changing the action method name.

ASP.NET
Code

  1. [HttpPost]  
  2. [ActionName("Index")]  
  3. public ActionResult Index_Post()  
  4. {  
  5.     if (ModelState.IsValid)  
  6.     {  
  7.         EmployeeModel obj=new EmployeeModel();  
  8.         UpdateModel(obj);  
  9.         ViewBag.SucessMessage = "Employee Info save" + "-" + obj.Emp_Id;  
  10.         return View();  
  11.     }  
  12.     return View();  
  13.   
  14. }  

Now with the help of above code that error will not come . Let's put the debugger and see the flow of UpdateFunction.

ASP.NET

ASP.NET

Model Class validation useing ModelState.IsValid propertie

ModelState.IsValid is responsible for the Model data validation.

Suppose that If we will enter the wrong data which will not map with Model class Field data type at that time it will return false.

Let's take the below example. Here our EmployeId is an integer type which will map with Our EmployeeModel class data field  Emp_Id  as integer type.

Now if we enter the EmployeeID as starting at that time it will throw the exception and ModelState will return as False.

ASP.NET
Now click on the submit button it will return as False, it means our input data is wrong.

ASP.NET

ASP.NET

Now if we enter the correct data we will not get that error.

ASP.NET

ASP.NET
Summary

That’s it! I hope it helps.