如何以编程方式触发或控制模型绑定

How Do I programmatically trigger or take control of model binding

我有上百种表格,@model Dictionary<string,CustomType_i>CustomType_i是表格的具体型号!

我没有为每个表单编写动作,而是尝试将它们提交给单个控制器动作。这是我尝试过的:

   public ActionResult ProcessForm(string formName, Dictionary<string,dynamic> mymodel){
  swich(formName){
    case "Customer":
    ///want to tell mvc to bind to Dictionary<string,Customer>
    break;
    case "Business":
    ///want to tell mvc to bind to Dictionary<string,Business>
    break;
  }

}

我尝试使用 .ToDictionary(kv => kv.Key, kv => kv.Value as Customer)myModel 转换为 Dictionary<string,Customer> 但它仍然为空,这可能意味着 none 键的类型为 Customer! 当我将 dynamic 更改为 Customer 时,它适用于 Customer 表单,而不适用于其他表单!

如何触发绑定到指定类型的模型?

您可以编写自己的 ModelBinder 扩展 IModelBinder 接口或 de DefaultModelBinder。

基本上你必须覆盖 BindModel 方法。

我觉得你应该这样写:

public class MyCustomBinder : DefaultModelBinder
{
    public object BindModel(ControllerContext controllerContext, 
                            ModelBindingContext bindingContext)
    {
        HttpRequestBase request = controllerContext.HttpContext.Request;

        if(string.IsNullOrWhiteSpaces(request.Form.Get("formName")))
        {
            switch(formName){
                case "Customer":
                /// Instantiate via reflection a Dictionary<string,Customer>
                ...
                // Return the object
                break;
                case "Business":
                ///Instantiate via reflection a Dictionary<string,Business>
                ...
                // Return the object
                break;
            }
        } 
        else
        {
            return base.BindModel(controllerContext, bindingContext);
        }
    }
}