C# 泛型类型的自定义模型绑定
我有一个ASP.NETMVC4应用程序,我正在尝试创建一个自定义模型绑定器。它必须处理的模式是:C# 泛型类型的自定义模型绑定,c#,asp.net-mvc,model-binding,C#,Asp.net Mvc,Model Binding,我有一个ASP.NETMVC4应用程序,我正在尝试创建一个自定义模型绑定器。它必须处理的模式是: public class CompressedJsonViewModel<T> where T : ViewModel 问题从这里开始。如果CompressedJsonViewModel未设置为“通用”,则以下对模型绑定器的指定将起作用: binders.Add(typeof(CompressedJsonViewModel), new CompressedJsonModelBi
public class CompressedJsonViewModel<T>
where T : ViewModel
问题从这里开始。如果CompressedJsonViewModel
未设置为“通用”,则以下对模型绑定器的指定将起作用:
binders.Add(typeof(CompressedJsonViewModel), new CompressedJsonModelBinder());
但是,当我将泛型T
添加到类signarture时,BindModel
方法不再被调用。我不知道如何设置正确的绑定。我尝试了两件事:
binders.Add(typeof(CompressedJsonViewModel<>), new CompressedJsonModelBinder());
两个都不起作用。找到了,但我觉得有点过分了。我想避免在参数中使用类似于
[ModelBinder(typeof(CompressedJsonModelBinder))]
的东西,我想做一些更自动化的东西。使用自定义ModelBinder提供程序
:
public class CompressedJsonBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
if(!modelType.IsGenericType)
return null;
var genericType = modelType.GetGenericTypeDefinition();
if(genericType == typeof(CompressedJsonViewModel<>))
return new CompressedJsonModelBinder();
return null;
}
}
公共类压缩DSONBinderProvider:IModelBinderProvider
{
公共IModelBinder GetBinder(类型modelType)
{
如果(!modelType.IsGenericType)
返回null;
var genericType=modelType.GetGenericTypeDefinition();
if(genericType==typeof(CompressedJsonViewModel))
返回新的CompressedJsonModelBinder();
返回null;
}
}
顺便说一句,这向您展示了机制,但我也会缓存te=he类型签入,以避免对每个请求都进行类型反射
binders.Add(typeof(CompressedJsonViewModel<>), new CompressedJsonModelBinder());
binders.Add(typeof(ICompressedJsonViewModel), new CompressedJsonModelBinder());
public class CompressedJsonBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
if(!modelType.IsGenericType)
return null;
var genericType = modelType.GetGenericTypeDefinition();
if(genericType == typeof(CompressedJsonViewModel<>))
return new CompressedJsonModelBinder();
return null;
}
}