Advertise with us

What is a MVC model binders?

Posted by  Anupam Mishra
 1230  View(s)
Rate this:
I want to know about MVC model binders and how to implement it in mvc.Please can anyone give me a solution.
Thank you.
  1. Re: What is a MVC model binders?

    Hi Anupam,
    Here we explaining about Model binders:
    Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model. Many times HTML UI names are different than the model property names.
     So in the binder we can write the mapping logic between the UI and the model.

    Now Bydefault, we call DefaultModelBinder class that are internally implement  IModelBinder interface.
    Here, a Student Model:
            public class Student
                public int ID { get; set; }
                [Display(Name = "FirstName")]
                public string FirstName { get; set; }
                [StringLength(50, MinimumLength = 1)]
                [Display(Name = "LastName")]
                public string LastName { get; set; }

    Here is the view which will be mapped with the Student model.


    @foreach (var item in Model) {
                @Html.DisplayFor(modelItem => item.FirstName)
                @Html.DisplayFor(modelItem => item.LastName)

    Create one class and implement IModelBinder interface within it. In the below snippet, we have created “StudentModelBinder ” custom binding class and implemented IModelBinder interface. We have seen that IModelBinder  contains only one method called BindModel and we have implemented the logic to map view property with the model property.

    public class StudentModelBinder : IModelBinder
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
                var request = controllerContext.HttpContext.Request;
                string first_name = request.Form.Get("FirstName");
                string last_name = request.Form.Get("LastName");
                return new Person { full_name = first_name + last_name };

    Here, we are combining first_name and last_name to combine full name and returning Student object accordingly. Fine, now we will create the controller which will contain PostData() action and as parameter, it will take Student type object after binding in our custom StudentModelBinder class. Here is the simple implementation.

    public class CustomodelbinderController : Controller
            public ActionResult Index()
                return View();
            public void PostData([ModelBinder(typeof(StudentModelBinder))] Student student)

    Now, we have to register the custom binder class in MVC pipeline. Now we Just add the below line in global.asax file.

    ModelBinders.Binders.Add(typeof(Student), new StudentModelBinder());] 

    Finally, we have setup everything to bind model using our custom class.

      Modified On Apr-11-2018 01:34:59 AM