2009-12-01 100 views
2

我有一个关于模型绑定在ASP.NET MVC(我使用MVC 2预览2)与继承有关的问题。ASP.NET MVC ModelBinding继承的类

说我有以下接口/类:

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

而且我有一个自定义的模型绑定BaseModelBinder。

以下做工精细:

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

下不工作(关于类型的子对象绑定一个):

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

有没有办法有一个模型粘结剂基类将适用于所有继承类?我真的不想为每个可能的继承类都手动输入一些东西。

此外,如果有可能,是否有一种方法来覆盖特定继承类的modelbinder?说我得到了这个工作,但我需要一个Child2的特定模型绑定器。

在此先感谢。

回答

5

我采取了一个简单的路线,我只是在启动时使用反射动态注册所有派生类。也许它不是一个干净的解决方案,但它的夫妇在初始化代码,只是工作;-)

线,但如果你真的想惹模型活页夹(你会HAVE至 - 最终 - 但有”更好的方式来花费你的时间;-)你可以阅读thisthis

+0

我想说这是一个更好的解决方案,减少不必要的副作用的风险。 – mrydengren 2009-12-04 10:27:40

1

嗯,我想这样做的一种方法是对ModelBindersDictionary类进行分类并覆盖GetBinders(Type modelType,bool fallbackToDefault)方法。

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; 
    } 
} 

基本上走的类层次结构,直到一个模型绑定发现或默认为DefaultModelBinder

下一步是使框架接受CustomModelBinderDictionary。据我可以告诉你需要分类以下三个类,并覆盖Binders属性:DefaultModelBinder,ControllerActionInvokerController。您可能想要提供自己的静态CustomModelBinders类。

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

更新

我猜的替代解决方案是定义你自己的CustomModelBindingAttribute

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

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