19

Is it possible to create a model binder for a generic type? For example, if I have a type

public class MyType<T>

Is there any way to create a custom model binder that will work for any type of MyType?

Thanks, Nathan

Nathan Roe
  • 844
  • 1
  • 8
  • 22

1 Answers1

27

Create a modelbinder, override BindModel, check the type and do what you need to do

public class MyModelBinder
    : DefaultModelBinder {

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

         if (HasGenericTypeBase(bindingContext.ModelType, typeof(MyType<>)) { 
             // do your thing
         }
         return base.BindModel(controllerContext, bindingContext);
    }
}

Set your model binder to the default in the global.asax

protected void Application_Start() {

        // Model Binder for My Type
        ModelBinders.Binders.DefaultBinder = new MyModelBinder();
    }

checks for matching generic base

    private bool HasGenericTypeBase(Type type, Type genericType)
    {
        while (type != typeof(object))
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
            type = type.BaseType;
        }

        return false;
    }
Anthony Johnston
  • 9,405
  • 4
  • 46
  • 57
  • 19
    Since this question still ranks pretty high on google's results, I'd like to mention that perhaps a better solution that has come out with MVC3 is to use [Model Binder Providers](http://bradwilson.typepad.com/blog/2010/10/service-location-pt9-model-binders.html). This makes is so that you don't have to replace the default binder if all you're doing is trying to add special rules for binding a _particular_ type, which makes custom model binding much more scalable. – DMac the Destroyer Sep 26 '11 at 21:26
  • I was struggling to find how to set custom model binder for all types in mvc 2 application. And here is the solution! Thanks a lot! – blazkovicz Feb 16 '12 at 08:10