【问题标题】:ASP.NET MVC Model Binder for Generic Type用于泛型类型的 ASP.NET MVC 模型绑定器
【发布时间】:2010-12-02 00:02:13
【问题描述】:

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

public class MyType<T>

有什么方法可以创建适用于任何类型的 MyType 的自定义模型绑定器?

谢谢, 内森

【问题讨论】:

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


    【解决方案1】:

    创建一个modelbinder,重写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;
        }
    

    【讨论】:

    • 由于这个问题在 google 的结果中仍然排名很高,我想提一下 MVC3 出现的更好的解决方案可能是使用Model Binder Providers。这样一来,如果您所做的只是尝试添加特殊规则来绑定 particular 类型,则无需替换默认绑定器,这使得自定义模型绑定更具可扩展性。
    • 我一直在努力寻找如何为 mvc 2 应用程序中的所有类型设置自定义模型绑定器。这是解决方案!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多