开发者

Add custom Model Binders for derived objects and their base

My class diagram:

BaseContentClass

  • Page inherits BaseContentClass
  • Tab inherits 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开发者_JAVA百科 custom model binder, do I? I don't know if I have any other option.


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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜