Asp.net mvc ASP.NET MVC ModelBinding继承的类

Asp.net mvc ASP.NET MVC ModelBinding继承的类,asp.net-mvc,inheritance,modelbinders,Asp.net Mvc,Inheritance,Modelbinders,我有一个关于ASP.NETMVC(我使用的是MVC2Preview 2)中与继承相关的模型绑定的问题 假设我有以下接口/类: interface IBase class Base : IBase interface IChild class Child: Base, IChild 我有一个自定义模型活页夹BaseModelBinder 以下工作将被罚款: ModelBinders.Binders[typeof(Child)] = new BaseModelBinder(); ModelBind

我有一个关于ASP.NETMVC(我使用的是MVC2Preview 2)中与继承相关的模型绑定的问题

假设我有以下接口/类:

interface IBase
class Base : IBase
interface IChild
class Child: Base, IChild
我有一个自定义模型活页夹BaseModelBinder

以下工作将被罚款:

ModelBinders.Binders[typeof(Child)] = new BaseModelBinder();
ModelBinders.Binders[typeof(IChild)] = new BaseModelBinder();
以下操作不起作用(在绑定Child类型的对象时):

有没有办法为基类提供一个适用于所有继承类的模型绑定器?我真的不想为每一个可能的继承类手动输入一些东西

此外,如果可能的话,是否有方法覆盖特定继承类的modelbinder?比如说,我让这个工作,但我需要一个特定的儿童2模型活页夹


提前感谢。

好吧,我想这样做的一种方法是对
ModelBindersDictionary
类进行子类化,并重写GetBinders(Type modelType,bool fallbackToDefault)方法

基本上遍历类层次结构,直到找到模型绑定器或默认为
DefaultModelBinder

下一步是使框架接受
CustomModelBinderDictionary
。据我所知,您需要对以下三个类进行子分类并重写Binders属性:
DefaultModelBinder
ControllerActionInvoker
Controller
。您可能希望提供自己的静态
CustomModelBinders

免责声明:这只是一个粗略的原型。我不确定它是否真的有效,它可能有什么影响,或者它是否是一个合理的方法。您可能希望自己下载框架的,然后进行实验

更新

我想另一种解决方案是定义自己的
CustomModelBindingAttribute

public class BindToBase : CustomModelBinderAttribute
{
    public override IModelBinder GetBinder()
    {
        return new BaseModelBinder();
    }
}

public class CustomController
{
   public ActionResult([BindToBase] Child child)
   {
       // Logic.
   }
}

我采取了一个简单的方法,我只是在启动时使用反射动态注册所有派生类。也许这不是一个干净的解决方案,但初始化代码中只有几行代码可以正常工作;-)


但是如果你真的想弄乱模型装订(你最终会有,但是有更好的方法来消磨你的时间;-)你可以阅读和阅读。

我认为这是一个更好的解决方案,没有不必要的副作用的风险。
public class CustomModelBinderDictionary : ModelBinderDictionary
{
    public override IModelBinder GetBinder(Type modelType, bool fallbackToDefault)
    {
        IModelBinder binder = base.GetBinder(modelType, false);

        if (binder == null)
        {
            Type baseType = modelType.BaseType;
            while (binder == null && baseType != typeof(object))
            {
                binder = base.GetBinder(baseType, false);
                baseType = baseType.BaseType;
            }
        }

        return binder ?? DefaultBinder;
    }
}
public class BindToBase : CustomModelBinderAttribute
{
    public override IModelBinder GetBinder()
    {
        return new BaseModelBinder();
    }
}

public class CustomController
{
   public ActionResult([BindToBase] Child child)
   {
       // Logic.
   }
}