C# 用于泛型类型的ASP.NET MVC模型绑定器
是否可以为泛型类型创建模型绑定器?例如,如果我有一个类型C# 用于泛型类型的ASP.NET MVC模型绑定器,c#,asp.net-mvc,generics,model-binding,C#,Asp.net Mvc,Generics,Model Binding,是否可以为泛型类型创建模型绑定器?例如,如果我有一个类型 public class MyType<T> 公共类MyType 有没有办法创建一个自定义的模型绑定器,可以用于任何类型的MyType 谢谢, Nathan创建一个modelbinder,重写BindModel,检查类型并执行需要执行的操作 public class MyModelBinder : DefaultModelBinder { public override object BindModel(
public class MyType<T>
公共类MyType
有没有办法创建一个自定义的模型绑定器,可以用于任何类型的MyType
谢谢,
Nathan创建一个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);
}
}
检查是否匹配泛型基
private bool HasGenericTypeBase(Type type, Type genericType)
{
while (type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
type = type.BaseType;
}
return false;
}
由于这个问题在谷歌的搜索结果中排名仍然很高,我想提一提的是,MVC3推出的一个更好的解决方案可能是使用。这使得您不必更换默认绑定器,如果您所做的只是尝试添加绑定特定类型的特殊规则,这使得自定义模型绑定更具可扩展性。我一直在努力寻找如何在mvc 2应用程序中为所有类型设置自定义模型绑定器。这就是解决办法!谢谢!
private bool HasGenericTypeBase(Type type, Type genericType)
{
while (type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
type = type.BaseType;
}
return false;
}