Create a modelbinder, override BindModel, check the type and do what you need to do
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);
}
}
Set your model binder to the default in the global.asax
protected void Application_Start() {
// Model Binder for My Type
ModelBinders.Binders.DefaultBinder = new MyModelBinder();
}
checks for matching generic base
private bool HasGenericTypeBase(Type type, Type genericType)
{
while (type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
type = type.BaseType;
}
return false;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…