What is a
model binder?
As we know, we can pass data from action to view through view data and view model. It's not one way and you can post data from view to action via form parameters, querystring, route parameters and etc. Model binders bind model to these data. All model binders implement IModelBinder interface directly or indirectly.
Custom model binders
Model binding is also one of the extensibility points in the MVC framework. If you can’t use the default binding behaviour you can provide your own model binders, and mix and match binders. To implement a custom model binder you need to implement the IModelBinder interface.
Use Case
Let us take an example where we have 3 text boxes which accepts day, month and year for a date but on submission of form we want our custom model binder to bind day,month and year in single date property.
Let us take an example where we have 3 text boxes which accepts day, month and year for a date but on submission of form we want our custom model binder to bind day,month and year in single date property.
Implementing
IModelBinder
public class CustomDateBinder : IModelBinder
{
Public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
string title = request.Form.Get("Title");
string day = request.Form.Get("Day");
string month = request.Form.Get("Month");
string year = request.Form.Get("Year");
return new DateModel()
{
Title = title,
Date = day + "/" + month
+ "/" + year
};
}
}
Our Date Model is as follows,
public class DateModel
public class DateModel
{
public string Title { get; set; }
public string Date { get; set; }
}
And Our Action is as follows,
[HttpPost]
public ActionResult CustomBinder(DateModel model)
{
return View();
}
Put the following line of code in the Application_Start()
of our global.asax
ModelBinders.Binders.Add(typeof(DateModel), new CustomDateBinder());
This tells MVC anytime we have a typeof(DateModel) as a
parameter in an action. We should use the CustomDateBinder to try and create an object
to fill the DateModel.
Output:
And on submission have a look at model,


No comments:
Post a Comment