Click here to Skip to main content
15,861,168 members
Articles / Web Development / HTML

Introduction to ASP.NET MVC Model Binding - An Absolute Beginner's Tutorial

Rate me:
Please Sign up or sign in to vote.
4.84/5 (61 votes)
14 Jan 2014CPOL5 min read 262.1K   2.7K   52   28
In this article we try to understand what is ASP.NET MVC Model Binding

Introduction

In this article we try to understand what is ASP.NET MVC Model Binding. We will look at some code samples to understand Model binding and why it is a very useful and essential for ASP.NET MVC application development.

Background

Whenever I talk to experiences ASP.NET Web Forms' developers(who recently started using ASP.NET MVC), I get one question quite often i.e. “How the values from HTML form(view) gets converted to the Model class when it reaches the Action method of the Controller class?”.

The answer to this question is that all this magic is being done by ASP.NET model binder. What Model binder does is that it takes the values coming from an HTML page and map it to a corresponding model. This is a very useful since it relieves the developers from writing all the “type casting” and “HTML-Model mapping” code. The Model binder is capable of retrieving the data from HTML form variables, POSTed variables and files, query string parameters and the values added in the routes.

It might seem a very simple task that we could have done ourselves without the need of Model Binder but in fact this mapping, if done manually, can become very time consuming, cumbersome and error prone. In this article, we will try to implement a simple solution without utilizing the Model binding and then we will try to see how Model binding saves us from writing a lot of mundane code.

Using the code 

Let us first look at the example where we will extract all the values form the Request and then populate our model manually. So first we need to create a Model. Let us create a simple Model class for Student.

C#
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DOB { get; set; }        
    public string FathersName { get; set; }
    public string MothersName { get; set; }
}

Now lets create a simple View which will contain a form to populate the Student details.

Image 1 

Now let us create simple Action methods in the StudentController to see how we get these values in the controller.

C#
public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        // TODO: Add insert logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}     

Now to let us fill some data in the HTML form and debug our Action method.

Image 2 

We can see that the values posted from the form are available in FormCollection as well as Request.Form. We can use any of these values to populate our Student Model. Let us go ahead and write some code to create the Student Model from the posted. Let us use FormCollection for this but we could have used Request.Form too.

C#
[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {   
        Student student = new Student();

        student.FirstName = collection["FirstName"];
        student.LastName = collection["LastName"];
        DateTime suppliedDate;
        DateTime.TryParse(collection["DOB"], out suppliedDate);
        student.DOB = suppliedDate;
        student.FathersName = collection["FathersName"];
        student.MothersName = collection["MothersName"];

        studentsList.Add(student);
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}        

Now in the above code snippet, we are extracting all the data from the HTML form's posted values and then mapping the values to the Student properties and assigning them. We are also doing the type casting where ever the supplied values are not of the same format as of the Model property. Now this doesn't look so bad. So Why do we need Model binder?

Consider following scenarios:

  1. Our Model contains a lot of properties and we need to manually map all of them.
  2. Our Model contains a lot of properties and we most of them need to type casting to be able to be assigned to Model properties.
  3. Our View is strongly typed to a View Model. We need to figure out which value goes to which Model(of ViewModel) and assign them manually.
  4. Our Model contains other Model object, The contained Model objects can in turn contain other model objects.
  5. The Model is a self referencing Model i.e. the Model contains an object of its own type.

Now the above mentioned scenarios are not that hypothetical that one might think. These are the scenarios that most deelopers encounter. Now imagine that in all these scenarios, if we need to perform the model binding manually. This is exactly where we can utilize the power and ease of use of ASP.NET MVC Model binding.

ASP.NET MVC Model all the data coming from HTTP world and use the DefaultModelBinder class which magically does all the type conversion and mapping of all these values to the Model properties. If we use Model binders then we dont have to write the conversion and mapping code which will lead to much cleaner code in our Controller class. Our Controller will then only need to worry about WHAT needs to be done to this received Model rather than HOW to create this Model.

Let us go ahead and use the Model Binder to perform the same operation we did earlier. What we need to do to use the Model Binder? We just need to change the papameter of Create Method to accept the Student Model object rather than FormCollection.

C#
[HttpPost]
public ActionResult Create(Student student)
{
    try
    {
        if (ModelState.IsValid)
        {
            studentsList.Add(student);
            return RedirectToAction("Index");
        }
    }
    catch
    {
        return View("Create");
    }

    return View("Create");
}    

Now the magic of Model Binding depends on the id of HTML variables that are supplying the values. For our student Model the id of the HTML input fields should be same as the Property names of the Student Model. The mapping will be based on the Property name by default. This is where we will find HTML helper methods very hepful because these helper methods will generate the HTML which will have proper Names for the Model Binding to work.

So to create the HTML input field for the Student FirstName property:

C#
@Html.EditorFor(model => model.FirstName)

And this will ensure that the generated HTML will have the proper Name so that the Model binder can understand it while retrieving the values. 

Image 3 

And thus we can see how using Model Binding and HTML helpers relieves us from writing a lot of mundane type conversion and model mapping code. If the default Model Binder is not working for us then we can implement our own custom Model Binder too. Also, One more thing to note is that if we need to get the values from some other provide than the default providers for instance we need to get some values from LocalStorage then we can also implement a custom value provider too.

Point of interest 

In this article, we have only discussed about what is ASP.NET Model Binding and saw a basic introduction to the Model Binder. The model binding process can be customized by implementing the custom model binder and value providers. But since this article is meant for the ASP.NET MVC absolute beginner's, these topics were not described in details here. I hope this article has been somewhat informative.

History

  • 15 January 2014: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
GeneralThank You! Pin
Priyanka Kale13-Feb-18 21:55
Priyanka Kale13-Feb-18 21:55 
QuestionEdit form in MVC 5 Asp.net Pin
Nitin Anand8-Apr-16 9:42
Nitin Anand8-Apr-16 9:42 
QuestionWhere did studentsList come from ? Pin
Babak Sekandari6-Apr-16 6:34
Babak Sekandari6-Apr-16 6:34 
GeneralMy vote of 5 Pin
Bananatie6-Oct-15 1:11
Bananatie6-Oct-15 1:11 
QuestionNice one but i have question... Pin
Member 1193088727-Sep-15 19:17
Member 1193088727-Sep-15 19:17 
QuestionModel Binding based on ID or Name attribute of Html ? Pin
Vishal P. Chavan12-Aug-15 22:08
Vishal P. Chavan12-Aug-15 22:08 
AnswerRe: Model Binding based on ID or Name attribute of Html ? Pin
Rahul Rajat Singh12-Aug-15 22:25
professionalRahul Rajat Singh12-Aug-15 22:25 
GeneralRe: Model Binding based on ID or Name attribute of Html ? Pin
Vishal P. Chavan13-Aug-15 3:03
Vishal P. Chavan13-Aug-15 3:03 
GeneralRe: Model Binding based on ID or Name attribute of Html ? Pin
Member 120616009-Jan-17 23:25
Member 120616009-Jan-17 23:25 
QuestionJust to correct Pin
Manu_Khanna7-Aug-15 4:23
professionalManu_Khanna7-Aug-15 4:23 
GeneralNice Article Pin
Dharmesh .S. Patil8-Jul-15 19:11
professionalDharmesh .S. Patil8-Jul-15 19:11 
Questiontryupdatemodel does not work with a model has fields instead of properties Pin
Member 105979216-Jul-15 13:04
Member 105979216-Jul-15 13:04 
QuestionNice work Pin
Mike Hankey20-Mar-15 1:15
mveMike Hankey20-Mar-15 1:15 
QuestionWhat the controller should receive when I am sending a view that contains multiple partial view with different models? Pin
Guillermo Sánchez6-Mar-15 12:36
Guillermo Sánchez6-Mar-15 12:36 
AnswerRe: What the controller should receive when I am sending a view that contains multiple partial view with different models? Pin
Rahul Rajat Singh8-Mar-15 18:16
professionalRahul Rajat Singh8-Mar-15 18:16 
QuestionGreat Explanation, My Vote of 5 but Pin
Mohammed Dawood Ansari29-Jan-15 17:20
Mohammed Dawood Ansari29-Jan-15 17:20 
AnswerRe: Great Explanation, My Vote of 5 but Pin
Rahul Rajat Singh29-Jan-15 17:31
professionalRahul Rajat Singh29-Jan-15 17:31 
QuestionExcellent demonstration Pin
jhonbv7729-Dec-14 3:41
jhonbv7729-Dec-14 3:41 
Generalgood work Pin
wajahatabdi11-Dec-14 20:27
wajahatabdi11-Dec-14 20:27 
Questionmodel variables Pin
hocka1020-Jul-14 21:15
hocka1020-Jul-14 21:15 
AnswerRe: model variables Pin
Rahul Rajat Singh20-Jul-14 21:20
professionalRahul Rajat Singh20-Jul-14 21:20 
GeneralRe: model variables Pin
hocka1020-Jul-14 21:36
hocka1020-Jul-14 21:36 
QuestionVery Smart Explanation Pin
Yaniv Chekroun25-Jun-14 22:41
Yaniv Chekroun25-Jun-14 22:41 
QuestionVery nice and clear explanation Pin
Peter Carrasco16-Jun-14 19:24
Peter Carrasco16-Jun-14 19:24 
AnswerArticle of the Day on Microsoft's site Pin
Rahul Rajat Singh18-May-14 18:28
professionalRahul Rajat Singh18-May-14 18:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.