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

时间:2015-11-04 14:36:48

标签: asp.net-mvc dynamic model-binding

我有数百种表单,@model Dictionary<string,CustomType_i> CustomType_i是特定于表单的模型!

而不是写一个foreach表单的动作,我试图将它们提交给单个控制器动作。这是我试过的:

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

}

我尝试使用myModelDictionary<string,Customer>转换为.ToDictionary(kv => kv.Key, kv => kv.Value as Customer),但它仍为null,这可能意味着没有任何键是Customer类型! 当我将dynamic更改为Customer时,它适用于客户表单的情况,而非其他表单!

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

1 个答案:

答案 0 :(得分:0)

您可以编写自己的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);
        }
    }
}