2009-09-28 63 views
19

是否可以为泛型类型创建模型绑定器?举例来说,如果我有一个类型通用类型的ASP.NET MVC模型绑定器

public class MyType<T> 

有什么办法来创建一个自定义模型粘结剂,将任何类型的MyType的工作吗?

感谢, 弥敦道

回答

25

创建一个模型绑定器,覆盖BindModel,检查型,做你需要做的

public class MyModelBinder 
    : DefaultModelBinder { 

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { 

     if (HasGenericTypeBase(bindingContext.ModelType, typeof(MyType<>)) { 
      // do your thing 
     } 
     return base.BindModel(controllerContext, bindingContext); 
    } 
} 

设置你的模型绑定到默认在Global.asax什么

protected void Application_Start() { 

     // Model Binder for My Type 
     ModelBinders.Binders.DefaultBinder = new MyModelBinder(); 
    } 

检查匹配通用基

private bool HasGenericTypeBase(Type type, Type genericType) 
    { 
     while (type != typeof(object)) 
     { 
      if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true; 
      type = type.BaseType; 
     } 

     return false; 
    } 
+16

由于这个问题在google的搜索结果中仍然排名很高,我想提一下,MVC3推出的更好的解决方案是使用[Model Binder Providers](http://bradwilson.typepad.com/)博客/ 2010/10 /服务的位置PT9模型-binders.html)。这样做的目的是,如果您正在尝试为绑定_particular_类型添加特殊规则,则不必替换默认绑定器,这使得自定义模型绑定的可扩展性更加可靠。 – 2011-09-26 21:26:34

+0

我一直在努力寻找如何为mvc 2应用程序中的所有类型设置自定义模型联编程序。这是解决方案!非常感谢! – blazkovicz 2012-02-16 08:10:58