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

时间:2009-09-28 13:24:58

标签: c# asp.net-mvc generics model-binding

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

public class MyType<T>

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

谢谢, 森

1 个答案:

答案 0 :(得分: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);
    }
}

将模型绑定器设置为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;
    }
相关问题