【问题标题】:Custom model binding for generic type泛型类型的自定义模型绑定
【发布时间】:2019-12-07 21:02:42
【问题描述】:

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

public class CompressedJsonViewModel<T>
    where T : ViewModel

将其作为 Action 中的参数接收为:

public ActionResult ImportData(CompressedJsonViewModel<ImportDataViewModel> input)

而且(目前)我有一个简单的活页夹,当配置好的时候我会改进它:

public class CompressedJsonModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        return base.BindModel(controllerContext, bindingContext);
    }
}

问题从这里开始。如果 CompressedJsonViewModel 未设置为通用,则以下分配给模型活页夹的工作:

binders.Add(typeof(CompressedJsonViewModel), new CompressedJsonModelBinder());

但是当我将泛型T 添加到类签名中时,不再调用BindModel 方法。我不知道如何设置正确的绑定。我尝试了两件事:

  1. 绑定为

    binders.Add(typeof(CompressedJsonViewModel<>), new CompressedJsonModelBinder());
    
  2. 创建一个接口为CompressedJsonViewModel : ICompressedJsonViewModel,并将其绑定设置为

    binders.Add(typeof(ICompressedJsonViewModel), new CompressedJsonModelBinder());
    

两者都不起作用。找到this,但对我来说似乎有些矫枉过正。我想避免在参数中使用[ModelBinder(typeof(CompressedJsonModelBinder))] 之类的东西,我想做一些比这更自动的东西。

【问题讨论】:

    标签: c# asp.net-mvc model-binding


    【解决方案1】:

    使用自定义ModelBinderProvider

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

    顺便说一下,这向您展示了机制,但我也会缓存 te=he 类型检查以避免必须对每个请求进行类型反射。

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2010-12-02
      相关资源
      最近更新 更多