R – ASP.NET MVC ModelBinding Inherited Classes

asp.net-mvcinheritancemodelbinders

I've got a question about ModelBinding in ASP.NET MVC (I'm using MVC 2 preview 2) related to inheritance.

Say I have the following interfaces/classes:

interface IBase
class Base : IBase
interface IChild
class Child: Base, IChild

And I have a custom model binder BaseModelBinder.

The following work fine:

ModelBinders.Binders[typeof(Child)] = new BaseModelBinder();
ModelBinders.Binders[typeof(IChild)] = new BaseModelBinder();

The following do not work (on binding a on object of type Child):

ModelBinders.Binders[typeof(Base)] = new BaseModelBinder();
ModelBinders.Binders[typeof(IBase)] = new BaseModelBinder();

Is there any way to have a model binder for a base class that will apply to all inherited classes? I really don't want to have to manually input something for every possible inheriting class.

Also, if it is possible, is there a way to override the modelbinder for a specific inheriting class? Say I got this working but I needed a specific modelbinder for Child2.

Thanks in advance.

Best Answer

I took a simple route, I just register all derived classes dynamically at startup using reflection. Maybe it's not a clean solution, but it's couple of lines in the initialization code that just works ;-)

But if you really want to mess with model binders (you'll HAVE to - eventually - but there're better ways to spend your time ;-) you can read this and this.