用于泛型类型的ASP.NET MVC模型绑定器

Nat*_*Roe 19 c# generics asp.net-mvc model-binding

是否可以为泛型类型创建模型绑定器?例如,如果我有一个类型

public class MyType<T>
Run Code Online (Sandbox Code Playgroud)

有没有办法创建一个适用于任何类型的MyType的自定义模型绑定器?

谢谢,内森

Ant*_*ton 26

创建一个模型绑定器,覆盖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);
    }
}
Run Code Online (Sandbox Code Playgroud)

将模型绑定器设置为global.asax中的默认值

protected void Application_Start() {

        // Model Binder for My Type
        ModelBinders.Binders.DefaultBinder = new MyModelBinder();
    }
Run Code Online (Sandbox Code Playgroud)

检查匹配的通用基础

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

        return false;
    }
Run Code Online (Sandbox Code Playgroud)

  • 由于这个问题在谷歌的搜索结果中仍然排名很高,我想提一下,MVC3推出的更好的解决方案是使用[Model Binder Providers](http://bradwilson.typepad.com/blog/2010) /10/service-location-pt9-model-binders.html).如果您正在尝试添加用于绑定_particular_类型的特殊规则,那么您无需替换默认绑定器,这使得自定义模型绑定更具可伸缩性. (18认同)