Можно ли создать модельное связующее для универсального типа? Например, если у меня есть тип
public class MyType<T>
Есть ли способ создать настраиваемое связующее устройство, которое будет работать для любого типа MyType?
Спасибо,
Натан
Ответ 1
Создайте модельный блок, переопределите 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;
}