Click here to Skip to main content
15,881,600 members
Articles / Interview

What is the Need of ASP.NET MVC Model Binders?

Rate me:
Please Sign up or sign in to vote.
4.40/5 (9 votes)
23 Jun 2021CPOL1 min read 37.5K   25   1
This post discusses the need of ASP.NET MVC model binders

Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model.

Image 1

Take the below simple HTML form example:

HTML
<formid="frm1" method=post action="/Customer/SubmitCustomer">
            Customer code :- <inputname="CCode"type="text"/>
            Customer name :- <inputname="CName"type="text"/>
    <input type=submit/>
</form> 

Now this form needs to fill the below “Customer” class model. If you see the HTML control name, it is different from the class property name. For example, HTML textbox control name is “CCode” and the class property name is “CustomerCode”. This mapping code is written in HTML binder classes.

C#
publicclassCustomer
{
publicstring CustomerCode { get; set; }
publicstring CustomerName { get; set; }
}

To create a model binder, we need to implement “IModelBinder” interface and mapping code needs to be written in the “BindModel” method as shown in the below code.

HTML
publicclassCustomerBinder : IModelBinder
{

publicobject BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;

string strCustomerCode = request.Form.Get("CCode");
string strCustomerName = request.Form.Get("CName");

returnnewCustomer
            {
                CustomerCode = strCustomerCode,
                CustomerName = strCustomerName
            };
}
}

Now in the action result method, we need to use the “ModelBinder” attribute which will attach the binder with the class model.

HTML
publicActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))]Customer obj)        
{

return View("DisplayCustomer");
}

If you are completely new to ASP.NET MVC, you can start with the free youtube video below which teaches MVC 5 from scratch.

Image 2

For further reading do watch the below interview preparation videos and step by step video series.

License

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


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
QuestionMy votes for 5 Pin
Gaurav Aroraa27-Oct-14 9:39
professionalGaurav Aroraa27-Oct-14 9:39 

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.