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:-
View:
<form id="frm1" method=post action=”/Customer/SubmitCustomer”>
Customer code :- <input name="CCode" type="text" />
Customer name :- <input name="CName" type="text" />
<input type=submit/>
</form>
Take the below simple HTML form example:-
View:
<form id="frm1" method=post action=”/Customer/SubmitCustomer”>
Customer code :- <input name="CCode" type="text" />
Customer name :- <input name="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 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.
Model Class:
public class Customer
{
public string CustomerCode { get; set; }
public string 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.
Model Binder Class:
public class CustomerBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext
bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
string strCustomerCode = request.Form.Get("CCode");
string strCustomerName = request.Form.Get("CName");
return new Customer
{
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.
Controller Class:
public ActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))]Customer obj)
{
return View(“DisplayCustomer”);
}

No comments:
Post a Comment