【发布时间】:2010-12-02 00:02:13
【问题描述】:
是否可以为泛型类型创建模型绑定器?例如,如果我有一个类型
public class MyType<T>
有什么方法可以创建适用于任何类型的 MyType 的自定义模型绑定器?
谢谢, 内森
【问题讨论】:
标签: c# asp.net-mvc generics model-binding
是否可以为泛型类型创建模型绑定器?例如,如果我有一个类型
public class MyType<T>
有什么方法可以创建适用于任何类型的 MyType 的自定义模型绑定器?
谢谢, 内森
【问题讨论】:
标签: c# asp.net-mvc generics model-binding
创建一个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;
}
【讨论】: