mare
mare

Reputation: 13083

Add custom Model Binders for derived objects and their base

My class diagram:

BaseContentClass

If I do this

ModelBinders.Binders.Add(typeof(BaseContentObject), new BaseContentObjectCommonPropertiesBinder());

then when in controller action parameter of type Tab appears, custom model binder is not fired.

It gets fired if I do this:

ModelBinders.Binders.Add(typeof(Tab), new BaseContentObjectCommonPropertiesBinder());

But I don't want to go writing "n" number of Add statements in my global.asax.cs to associate all the derived classes with my custom model binder, do I? I don't know if I have any other option.

Upvotes: 2

Views: 1139

Answers (2)

Jab
Jab

Reputation: 13775

Try doing this instead. I haven't tested it, but I'm fairly certain it will work.

[ModelBinder(typeof(BaseContentObjectCommonPropertiesBinder))]
public class BaseContentObject {}

Upvotes: 2

Richard McGuire
Richard McGuire

Reputation: 11090

The ModelBinders.Binders property is of type ModelBinderDictionary which uses the type as a key. As a result it will ignore you registering the model binder for the base class. Reading this article from Los Techies I think you might be able to get around this by defining a binder attribute upon the type, see the order precedence in the article.

Upvotes: 2

Related Questions