用于generics类型的ASP.NET MVC模型绑定器
是否可以为generics类型创建模型绑定器? 例如,如果我有一个类型
public class MyType
有没有办法创建一个适用于任何类型的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; }