Thursday, June 12, 2014

Explain MVC model binders ? ( ASP.NET MVC interview questions)

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



Take the below simple HTML form example :-








Now this form needs to fill the below “Customer” class model. If you see the HTML control name they are 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.

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.

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.

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

return View(“DisplayCustomer”);
}

This MVC interview question was provided by questpond which conducts ASP.NET MVC training . In case you are new to MVC you can start from questpond video which is shown below.

3 comments:

Unknown said...

nice post.. thanks for sharing.

ASP.Net training

Unknown said...

Great information. Thanks for sharing

.Net training in Lucknow

Unknown said...

useful information. Thanks for sharing. I have bookmark your blog for future updates.

.Net training in Lucknow