Skip to main content

Model Binding in MVC

In routing you know how to define parameter for request {controller=Home}/{action=Index}/{id} but does you know, how the requested url data (for id parameter) we get in action id parameters?
for eg.
public ViewResult GetClientById(int id){...}

Model Binding is a process where data from HTTP request maps with action parameters.

There are 3 ways to send the data using HTTP request and model binding order
- Form values
- Route values
- Query strings

Form values:
If you saying form values then action parameter should be complex type like Customer model.
So, how model binding for form work?
HomeController.cs
public  class HomeController: Controller
{
   public ViewResult SaveCustomer(Customer customer){....}
}

HTML
<input type='text' id='firstName' name ='firstName' />

.cs
public class Customer
{
     public string firstName {get; set;}
}

When a HTTP request come, model binding map the form controls values with the action parameter Customer model. First it look for the name property of the control and map its value with same name property in Customer model.
HTML helper methods helpful in that case
@Html.EditorFor(model => model.firstName)

It will generate text field with equivalent control name
<input type='text' id='firstName' name='firstName' value='' />

Route values:
In case of route values model binding match the route values with action parameter
for eg.
Route Table
{controller=Home}/{action=Index}/{id}

Action method
public ViewResult Index(int id){...}

HTTP Request
http://www.LearnOnlineAsp.Net/Home/Index/5

Query strings:
Model binding splits the key and values from request url query string and map with Action parameters.
eg.
Action Method
public ViewResult SaveCustomer(string firstName){...}

HTTP Request
http://www.LearnOnlineAsp.Net/Home/Index?id =5

Here I explained only the basic level of Model binding with minimum words and hope it help you start with Model Binding concept in MVC.