Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 泛型类型的自定义模型绑定_C#_Asp.net Mvc_Model Binding - Fatal编程技术网

C# 泛型类型的自定义模型绑定

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

我有一个ASP.NETMVC4应用程序,我正在尝试创建一个自定义模型绑定器。它必须处理的模式是:

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;        
       }
    }