ASP.NET MVC模型绑定的泛型类型
-
18-09-2019 - |
题
是否有可能创建一个通用型的模型粘合剂?例如,如果我有一个类型
public class MyType<T>
有什么办法来创建一个自定义模型粘结剂,将任何类型的MyType的?
工作谢谢, 森
解决方案
创建模型绑定器,覆盖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;
}
不隶属于 StackOverflow