Model Binder in Asp.Net MVC

by Sachin Singh


Posted on Saturday, 28 March 2020

Tags: model binding model binding in mvc model binding in asp.net mvc model binding in C# mvc what is model binding in mvc What Model Binder in MVC Custom Model Binder How model binder works internally

Model Binder is the mechanism which converts the URL segment into method Parameters.

It acts as a bridge between http request and Action Method and map the values from URL which may be within the sort of QueryString ,Routed Data or Posted Data [Form collection] to Action Parameters.

The parameters can be of primitive Type or Complex Type like Employee, Contact etc.

Model Binder uses Default Model Binder for mapping.

It follows the below rule for mapping.
  1. Request.Form[]:-If request is a post request.
  2. RouteData.Values[]:- If value is in the route.
  3. Request.QueryString[]:-if values are concatenated in the URL as querystring. .
  4. Request.Files[]:-If file is being uploaded.

Let's understand it with various examples and you will realize how model binder has made developer's life easier.

First Example:-

Get Request with Routed Data without ModelBinder.

Get Route Value from URL
Get Route Value from URL

As you can see from figure that if we don't pass Id as parameter ,Then we have to use old ASP way to get route value which is a bit hectic.

Get Request with Routed Data with ModelBinder.

Get Route Value from URL
Get Route Value from URL

From figure you can see when we pass Id as method parameter we do not need to do anything and the Route value gets automatically mapped,This is the power of model Binder.

Second Example:-

Get Request with QueryString without ModelBinder.

Get QueryString Value From URL
Get QueryString Value From URL

As you can see from figure,if we don't pass Id as method parameter then In old ASP way we have to use Request object QueryString method to retrieve Id value from URL ,which is hectic.

Get Request with QueryString with ModelBinder.

Get QueryString Value From URL
Get QueryString Value From URL

As you can see from above figure when we pass Id as method parameter we do not need to do additional work to retrieve QueryString value from URL ,ModelBinder takes care of it.

Third Example:-

Post Request without Model Binder.

Form for Post Request
Form For Post Request
Retrieve values from Form collection
Retrieve values from Form collection

As you can see from above figure, how hectic work it becomes when we don't pass Employee Type as method parameter .we have to use Form collection of request object to retrieve posted values in old ASP fashion.

Post Request with Model Binder.

Employee Type as Method Parameter
Model Binder for Form Collection

As you can observe from the above figure that how easy it becomes to get value from Form collection when we pass Employee Type as method parameter.

The Model Binder binds each property of the employee object by matching the html control's Name with property Name.

What if the html control's have different Names than Class properties.

In real world ,UI designer are different people and developers are different. Usually the UI designer follows a naming convention for Html controls like txtName for TextBox and ddlCity for Dropdown etc.

But A Model in our application represents a real world Entity like employee or Customer etc so the property name is accordingly represents a real characteristic of that Entity.So the possibility becomes high that Html control's will have different Name than Class properties.

In this situation MVC allows us to write our own Custom Model Binder.

Custom Model Binder:-

When UI control's have different Name than Our class property then we have to make our own Model Binder by Implementing IModelBinder interface like below.


    public class EmployeeModelBinder:IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var obj = controllerContext.HttpContext;
            string _Name=obj.Request.Form["txtName"];
            string _Gender = obj.Request.Form["txtGender"];
            int _Id=Convert.ToInt32(obj.Request.Form["txtId"]);
            int _Age = Convert.ToInt32(obj.Request.Form["txtAge"]);
            Employee emp = new Employee()
            {
                Name = _Name,
                Gender = _Gender,
                Age = _Age,
                Id = _Id
            };
            return emp;
        }
    }


    <form action="/Student/SaveEmployee" method="post">
    Id: <input type="number" name="txtId" value="" />
    Name: <input type="text" name="txtName" value="" />
    Gender: <input type="text" name="txtGender" value="" />
    Age: <input type="number" name="txtAge" value="" />
    <button type="submit">Save</button>
    </form>

As you can see ,i have changed the html control's name as per naming convention which is different from properties name in Employee class.

But ,on running the application it is working as earlier due to custom model binder.

Custom Model Binder
Custom Model Binder