Model view controller 在自定义模型绑定中应该覆盖哪些方法或属性?

Model view controller 在自定义模型绑定中应该覆盖哪些方法或属性?,model-view-controller,defaultmodelbinder,custom-model-binder,Model View Controller,Defaultmodelbinder,Custom Model Binder,我有一个MVC应用程序的自定义绑定场景,它需要两项功能 1) 一种通用的、可重用的自定义活页夹,允许表单/查询属性映射到类属性 2) 一种特定于类的自定义活页夹,将给定的表单/查询参数拆分为一个字典(或两个属性) 第一个要求是通过我通过谷歌找到的解决方案实现的(很抱歉,我无法提供链接,因为我忘了在哪里找到它) 本质上,有两部分 public class BindAliasAttribute : Attribute { ... public string Alias { get;

我有一个MVC应用程序的自定义绑定场景,它需要两项功能

1) 一种通用的、可重用的自定义活页夹,允许表单/查询属性映射到类属性

2) 一种特定于类的自定义活页夹,将给定的表单/查询参数拆分为一个字典(或两个属性)

第一个要求是通过我通过谷歌找到的解决方案实现的(很抱歉,我无法提供链接,因为我忘了在哪里找到它)

本质上,有两部分

public class BindAliasAttribute : Attribute {
    ...
    public string Alias { get; set; }
    ...
}
这就像

public class SearchRequest {
   ...
   [BindAlias("q")]
   public string SearchTerms { get; set; }
   ...
}
第二件是

public class AliasModelBinder : DefaultModelBinder {
   ...
   protected override ProperyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) {
      var returnProps = base.GetModelProperties(controllerContext, bindingContext);

      // check model for properties with alias attribute
      // add additional PropertyDescriptors as needed
   }
   ...
}
我的问题是需求2。在本例中,SearchRequest类上还有一个附加属性

public class SearchRequest {
   ...
   [BindAlias("q")]
   public string SearchTerms { get; set; }
   ...
   [BindAlias("s")]
   public IDictionary<string, string> SortOrder { get; set; }
   ...
}
绑定表单/查询值所需的逻辑如下

// loop through each form/query parameter of SortOrder or s
// get the value and split it on the space
// add thw two split values to the SortOrder property as new dictionary item
我知道我应该再次从DefaultModelBinder继承…或者在本例中是AliasModelBinder(它又从DefaultModelBinder继承)以支持别名,但我的问题是我不确定要覆盖哪个方法。关于重复使用DefaultModelBinder的最佳方法,似乎只有很少(即几乎没有)的信息

我的另一个问题涉及使用两个自定义模型绑定器的最佳方式。据我所知,没有模型绑定链接。我有没有办法在不明确了解解决方案1的情况下完成需求2?需求#2关心的是获取单个值并将其拆分为字典。SortOrder属性的值是否真的来自别名表单/查询参数

任何帮助都将不胜感激

多谢各位


Jason

我主要重写了OnModelUpdated(),在某些情况下,我不得不重写BindModel,但很少。在OnModelUpdated中,您的模型已经水合,但是您仍然可以以任何您认为合适的方式对其进行更改,并且可以完全访问控制器和ModelBinding上下文。

因此,根据您的建议,在调用OnModelUpdated方法时,将创建模型并设置所有可以设置的属性。那时,我应该“回填”SortOrder属性?是的,这就是我的意思。虽然我没有使用那个特殊的方法,但我使用了让默认逻辑创建模型,然后添加我的特殊逻辑的一般思想。本质上,你确认了我最初的方法。谢谢。很高兴能帮上忙:)
// loop through each form/query parameter of SortOrder or s
// get the value and split it on the space
// add thw two split values to the SortOrder property as new dictionary item