2009-09-28 40 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