通用类型的自定义模型绑定

时间:2019-07-30 12:52:27

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

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

public class CompressedJsonViewModel<T>
    where T : ViewModel

要以以下方式在操作中将其作为参数接收:

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,但对我来说似乎有些矫kill过正。我想避免在参数中使用诸如[ModelBinder(typeof(CompressedJsonModelBinder))]之类的东西,我想使之变得更 automatic

1 个答案:

答案 0 :(得分:1)

使用自定义var score = inSheet.getRange(inRow, colNoScore).getValue();

ModelBinderProvider

顺便说一句,这向您展示了机制,但是我还要缓存te = he类型检查,以避免必须对每个单个请求进行类型反映。

相关问题