ASP.NET MVC 通用类型模型绑定器

19

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

public class MyType<T>

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

谢谢, Nathan

1个回答

27
创建一个模型绑定器,覆盖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;
    }

19
由于这个问题在谷歌搜索结果中仍然排名很高,我想提一下,也许 MVC3 出现了一个更好的解决方案,即使用模型绑定程序提供程序。 这样做可以避免替换默认绑定程序,如果你只是尝试添加特殊规则以绑定某种类型,这会使自定义模型绑定更具可伸缩性。 - DMac the Destroyer
我曾经苦苦寻找如何为MVC 2应用程序设置自定义模型绑定器的方法。现在,问题终于得到了解决!非常感谢! - blazkovicz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接