2015-11-04 110 views
-1

我有幾百個表單,其中@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; 
    } 

}

我曾嘗試使用.ToDictionary(kv => kv.Key, kv => kv.Value as Customer)但它仍然是零,這或許意味着沒有密鑰的類型客戶的myModelDictionary<string,Customer>轉換! 當我將dynamic更改爲Customer時,它適用於客戶表單的情況,而不是其他表單的情況!

如何觸發模型綁定到指定的類型?

+0

的'DefaultModelBinder'結合模型之前執行在方法的任何代碼。它太晚了,綁定已經失敗,因爲它不能綁定到'dynamic'。雖然你可以編寫你自己的模型綁定器,但它比每個視圖有一個'ActionResult'方法的代碼要多得多。 –

回答

0

您可以編寫自己的ModelBinder,擴展IModelBinder接口或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); 
     } 
    } 
}