A better Model Binder

One of the more interesting extension points in ASP.NET MVC are the Model Binders.  Model Binders are tasked with transforming the HTTP Form and Querystring information and coercing real .NET types out of them.  A normal POST is merely a set of string key-value pairs, which isn’t that fun to work with.

Back in the ASP 3.0 days, where I cut my teeth, we did a lot of “Request.Form(“CustFirstName”)” action, and just dealing with the mapping from HTTP to strong types manually.  That wasn’t very fun.

ASP.NET MVC supplies the DefaultModelBinder, which is able to translate HTTP request information into complex models, including nested types and arrays.  It does this through a naming convention, which is supported at both the HTML generation (HTML helpers) and the consumption side (model binders).

Reconstituting complex model objects works great, especially in form posting scenarios.  But there are some scenarios where we want more complex binding, and for these scenarios, we can supply custom model binders.

Quick glance at custom model binders

ASP.NET MVC allows us to override both the default model binder, as well as add custom model binders, through the ModelBinders static class:

ModelBinders.Binders.DefaultBinder = new SomeCustomDefaultBinder();
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());

The custom binders are bound by destination type.  We can also use the Bind attribute to supply the type of the custom binder directly on our complex model type.  The resolution code (from CodePlex) is:

private IModelBinder GetBinder(Type modelType, IModelBinder fallbackBinder)
{
    // Try to look up a binder for this type. We use this order of precedence:
    // 1. Binder registered in the global table
    // 2. Binder attribute defined on the type
    // 3. Supplied fallback binder

    IModelBinder binder;
    if (_innerDictionary.TryGetValue(modelType, out binder))
    {
        return binder;
    }

    binder = ModelBinders.GetBinderFromAttributes(modelType,
        () => String.Format(CultureInfo.CurrentUICulture, MvcResources.ModelBinderDictionary_MultipleAttributes, modelType.FullName));

    return binder ?? fallbackBinder;
}

Very nice, they even commented the order of precedence!

This is all well and good, but the custom model binding resolution leaves me wanting.  It only works if the destination type matches exactly with a type registered in the custom binder collection.  That’s great, unless you want to use something like binding against a base class, such as a layer super type of Entity or similar.  Suppose I want to bind all Entities by fetching them out of a Repository automatically?  That would allow me to just put our entity types as action parameter types, instead of GUIDs littered all over the place.  It gets even worse as some ORMs (NHibernate being one) use proxies to do lazy loading, and the runtime type is some crazy derived type you’ve never heard of.

But we can do better.

A new default binder

Instead of using the ModelBinders.Binders.Add method, let’s put all of our matching in our default binder, a new binder, a SmartBinder.  This SmartBinder can still have all the default binding logic, but this time, it will attempt to match individual custom binders themselves.  To do this, let’s define a new IModelBinder interface:

public interface IFilteredModelBinder : IModelBinder
{
    bool IsMatch(Type modelType);
}

Instead of our ModelBinderDictionary containing the matching logic, let’s put this where I believe it belongs – with each individual binder.  Model binders make a ton of assumptions about what the model information posted looks like, it makes sense that it’s their decision on whether or not they can handle the model type trying to be bound.  We created a new IFilteredModelBinder type, inheriting from IModelBinder, and added an IsMatch method that individual binders can use to match up their type.

The new SmartBinder becomes very simple:

public class SmartBinder : DefaultModelBinder
{
    private readonly IFilteredModelBinder[] _filteredModelBinders;

    public SmartBinder(IFilteredModelBinder[] filteredModelBinders)
    {
        _filteredModelBinders = filteredModelBinders;
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        foreach (var filteredModelBinder in _filteredModelBinders)
        {
            if (filteredModelBinder.IsMatch(bindingContext.ModelType))
            {
                return filteredModelBinder.BindModel(controllerContext, bindingContext);
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }            
}

Our new SmartBinder depends on an array of IFilteredModelBinders.  This array is configured by our IoC container of choice (StructureMap in my case), so our SmartBinder doesn’t need to concern itself on how to find the right IFilteredModelBinders.

The BindModel method is overridden, and simply loops through the configured filtered model binders, asking each of them if they are a match to the model type attempting to be resolved.  If one is a match, its BindModel method is executed and the value returned.

If there are no matches, the logic defaults back to the built-in DefaultModelBinder progression, going through the commented steps laid out before.

I’ve found that our custom model binders can decide to bind a certain model for quite a variety of reasons, whether it’s a specific layer supertype and the types are assignable, or maybe the type is decorated with a certain attribute, it’s really up to each individual filtered model binder.

That’s the strength of this design – it puts the decision of what to bind into each individual model binder, providing as much flexibility as we need, instead of relying specifically on only one matching strategy, on concrete type.  Now testing custom model binders – that’s another story altogether.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in ASP.NET MVC. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://iridescence.no Fredrik Kalseth

    That’s much nicer. I totally agree that its better to have the binders decide whether they can handle some type or not (IsMatch). This of course redefines the order of precedence, so you have to think about the order in which you register the binders – or rather, the order in which the container injects them.

  • http://amandabynesnudiesny.xanga.com lilikindsli

    YcWT6r I want to say – thank you for this!

  • Daniel Silva

    How can a ModelBinder use my factory method, or standalone factory?
    I´m getting confused when using ModelBinder’s utility, but some properties have default initialization values required…

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Daniel

    Not sure I understand the question….can you explain a little more?

  • http://danbowles.com Dan

    Could you possibly post the code/link for the StructureMap side of things? I’m very new to it, but I am using now in a project and I’d like to see how you integrated it into your SmartBinder.

    Thanks!

  • http://www.kitchaiyong.net kitchaiyong

    nice and cool.

  • Hambone

    Sorry for resurrecting an old post, but how do you:

    a) set SmartBinder as the DefaultBinder in your global.asax.cs?
    b) manage your various IFilteredModelBinders, esp. how you configure them into StructureMap and get them injected as an array into the SmartBinder’s constructor?

  • Nasim

    Nice !! Thanks  a lot

  • Ahole

    Where some source code to download and project
    lol as usual just another crapola worth article by a unit inch goat humping ahol