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.
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.
- Form Collection
- 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.
And select the MVC template with individual User account.
Let add the home controller with index action method.
Step 1
- public ActionResult Index()
- {
- return View();
- }
-
- [HttpPost]
- public ActionResult Index(int Emp_Id, string Emp_Name, String Emp_Add)
- {
-
- ViewBag.SucessMessage = "Employee Info save" + Emp_Id;
- return View();
-
- }
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>
-
- }
Step3
Now our code is ready for run .press f5 and sees the output.
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 .
Ones we click on the submit button control will go to Post Index action method with the captured form’s data.
Now we can see that Form Collection captures the form’s data value.
Cons of form collection:
- It’s not suitable if our number of input field increases
- 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.
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; }
- }
- }
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.
Click the submit button.
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,
- [HttpPost]
-
- 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.
Action Name attribute is responsible for changing the action method name.
Code
- [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();
-
- }
Now with the help of above code that error will not come . Let's put the debugger and see the flow of UpdateFunction.
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.
Now click on the submit button it will return as False, it means our input data is wrong.
Now if we enter the correct data we will not get that error.
Summary
That’s it! I hope it helps.