As mentioned in my previous article, creating a custom ModelBinder is a piece of cake. You simply implement an interface and then write your own implementation of a method. A template might look something like this:
public class YourCustomModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var modelToBind = new YourCustomViewModel() ;
/// implementation goes here
return modelToBind ;
}
}
In your implementation code, you could read values out of the controllerContext and bind them to your object like so:var integers = controllerContext.HttpContext.Request.Form["integers"]
Typically when you create a custom ModelBinder, it is only created to coerce the values of 1 or 2 specific properties. In other words, generally, most of the desired binding behavior can still be met by the default binders in ASP.NET MVC. Park that thought!If you also remember from the previous article, when we register a custom ModelBinder, we do so using the following registration code in App_Start:
So from seeing this, we can determine that ASP.NET MVC already knows information about the base type that we are wishing to construct; in this case, that type is of type "YourCustomViewModel".ModelBinders.Binders[typeof(YourCustomViewModel)] = new YourCustomViewModelBinder();
Given what we know:
- ASP.NET MVC knows what type we want to create based on our controller context
- The default model binder could handle most of the binding for us
We can rewrite our first implementation to use the following code:
public class YourCustomModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var model = ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext) as YourCustomViewModel;
/// implementation goes here
return model ;
}
}
You can see in the line of code that has changed that I've used the DefaultBinder to bind all of the values it can and to return them to me in an object which is of the type that we are expecting.Using the second approach means that I only have to wire-up an implementation for the properties that the default binders cannot provide. For large, custom view models, this can save a lot of unnecessary binding code for mapping things such as simple Dates, Integers, Strings, etc.
Further Reading:
- There's lots of links to articles about this topic here.
No comments:
Post a Comment