ModelbindingMVC.md - brainchildservices/curriculum GitHub Wiki

SLIDE-1

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

SLIDE-2

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.

Screenshot 2021-06-19 at 12 31 24 PM

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.

  • Form Collection
  • Model binding

SLIDE-3

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.

Screenshot 2021-06-19 at 12 36 20 PM

SLIDE-3(DOWNWARDS)

And select the MVC template with individual User account.

Screenshot 2021-06-19 at 12 39 45 PM

Let add the home controller with index action method.

 public ActionResult Index()  
 {  
     return View();  
 }  
 /*Form data submission with simple type binding*/  
 [HttpPost]  
 public ActionResult Index(int Emp_Id, string Emp_Name, String Emp_Add)  
 {  
     ViewBag.SucessMessage = "Employee Info save" + Emp_Id;  
     return View();  

 }  

SLIDE-4

Step 2

Creating the view

 @{  
     ViewBag.Title = "Home Page";  
 }  

 <div class="jumbotron">  
     <strong>ASP.NET MVC</strong>  
 </div>  

 <tr class="form-group">  
     @using (Html.BeginForm())  
     {  
         <table align="center">  
             <tr >  
                 <td align="center">  
                     @Html.Label("EmployeeID:")  
                     @Html.TextBox("Emp_Id")  
                 </td>  
             </tr>  
             <tr>  
                 <td align="center">  
                     @Html.Label("EmployeeName:")  
                     @Html.TextBox("Emp_Name")  
                 </td>  
             </tr>  
             <tr>  
                 <td align="center">  
                     @Html.Label("EmployeeAdd:")  
                     @Html.TextBox("Emp_Add")  
                 </td>  
             </tr>  
             <tr>  
                 <td align="center">  
                     <input type="submit" value="Submit" class="btn-primary" />  
                 </td>  
             </tr>  
             <tr>  
                 <td>  
                     @ViewBag.SucessMessage  
                 </td>  
             </tr>  

         </table>  

     }  

SLIDE-5

Step3

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

Screenshot 2021-06-19 at 12 39 45 PM

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.

SLIDE-5(DOWNWARDS)

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

Screenshot 2021-06-19 at 12 45 14 PM

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

SLIDE-5(DOWNWARDS)

Screenshot 2021-06-19 at 12 46 06 PM

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.

SLIDE-6

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.

Screenshot 2021-06-19 at 12 48 47 PM

SLIDE-7

Step 2

Model class(EmployeeModel) add the required filed.

 using System;    
 using System.Collections.Generic;    
 using System.Linq;    
 using System.Web;    
 namespace MVC_ModelBinding.Models    
 {    
     public class EmployeeModel    
     {    
         public int Emp_Id { get; set; }    
         public string Emp_Name { get; set; }    
         public string  Emp_Add { get; set; }   
     }    
 } 

SLIDE-8

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

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

Note

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

Let put the debugger and see the capture values.

Screenshot 2021-06-19 at 12 51 19 PM

SLIDE-8(DOWNWARDS)

Click the submit button.

Screenshot 2021-06-19 at 12 51 57 PM

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

SLIDE-9

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,

 [HttpPost]    
 /* Binding With Update model*/    
 public ActionResult Index()    
 {    
     if (ModelState.IsValid)    
     {    
         EmployeeModel obj=new EmployeeModel();    
         UpdateModel(obj);    
         ViewBag.SucessMessage = "Employee Info save" + "-" + obj.Emp_Id;    
         return View();    
     }    
     return View();  
 } 

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.

SLIDE-10

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

Screenshot 2021-06-19 at 12 53 50 PM

 [HttpPost]  
 [ActionName("Index")]  
 public ActionResult Index_Post()  
 {  
     if (ModelState.IsValid)  
     {  
         EmployeeModel obj=new EmployeeModel();  
         UpdateModel(obj);  
         ViewBag.SucessMessage = "Employee Info save" + "-" + obj.Emp_Id;  
         return View();  
     }  
     return View();  
 }  

SLIDE-11

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

Screenshot 2021-06-19 at 12 55 01 PM

Screenshot 2021-06-19 at 12 55 38 PM

SLIDE-12

Model Class validation using ModelState.IsValid property

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.

Screenshot 2021-06-19 at 12 59 31 PM

SLIDE-12(DOWNWARDS)

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

Screenshot 2021-06-19 at 12 59 53 PM

SLIDE-12(DOWNWARDS)

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

Screenshot 2021-06-19 at 1 00 09 PM

⚠️ **GitHub.com Fallback** ⚠️