2013-06-26 13 views
1

我有一個看起來像爲什麼我無法爲列表<int>註冊自定義模型聯編程序?

public ActionResult GetUsers(List<int> userIds) {//do stuff} 

的用戶id列表可以成爲相當長一個動作,所以我想用Json.Net來反序列化。爲此,我創建了一個IModelBinder實現,該實現可以很好地適用於其他對象,但從不會被調用List。該IModelBind看起來像這樣

public class JsonBinder : System.Web.Mvc.IModelBinder 
{ 
    public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext) 
    { //Do model binding stuff using Json.Net } 
} 

我註冊這個模型綁定這一行

ModelBinders.Binders.Add(typeof(List<int>), new JsonBinder()); 

然而JsonBinder永遠不會被調用。爲什麼是這樣?我應該使用ValueProvider嗎?

+0

你檢查isn't被改寫爲類型列表''模型粘合劑?您可以嘗試在全局的Application_Start事件結束時註冊它。asax –

+0

我不確定如何檢查模型聯編程序是否被覆蓋。模型聯編程序的註冊在Application_Start事件結束時完成。 – quarksoup

回答

1

添加在Global.asax中以下事件(或代碼添加到您現有的Application_BeginRequest處理程序):

protected void Application_BeginRequest() 
{ 
    foreach (var type in ModelBinders.Binders.Keys) 
    { 
     System.Diagnostics.Trace.WriteLine(
           String.Format("Binder for '{0}': '{1}'", 
              type.ToString(), 
              ModelBinders.Binders[type].ToString())); 
    } 

} 

然後你可以在什麼粘合劑當前註冊的VS輸出窗口查詢。你可以看到這樣的事情:

Binder for 'System.Web.HttpPostedFileBase': 'System.Web.Mvc.HttpPostedFileBaseModelBinder' 
Binder for 'System.Byte[]': 'System.Web.Mvc.ByteArrayModelBinder' 
Binder for 'System.Data.Linq.Binary': 'System.Web.Mvc.LinqBinaryModelBinder' 
Binder for 'System.Threading.CancellationToken': 'System.Web.Mvc.CancellationTokenModelBinder' 

你也可以檢查是否有可能被選擇的粘合劑提供任何ModelBinderProvider,因爲使用該模型粘合劑用於選擇的順序如下:

  1. 動作參數的屬性。請參閱ControllerActionInvoker class的GetParameterValue方法

  2. 從IModelBinderProvider返回的活頁夾。請參見ModelBinderDictionary class中的GetBinder方法

  3. 活頁夾全局註冊在ModelBinders.Binders字典中。

  4. 在模型類型的[ModelBinder()]屬性中定義的活頁夾。

  5. DefaultModelBinder。

使用類似的方法來檢查模型綁定提供商在BeginRequest事件:

foreach (var binderprovider in ModelBinderProviders.BinderProviders) 
{ 
    System.Diagnostics.Trace.WriteLine(String.Format("Binder for '{0}'", binderprovider.ToString())); 
} 

此外,您可以嘗試通過的NuGet添加Glimpse,作爲一個選項卡可提供有關模型信息綁定器用於控制器操作中的每個參數。

希望這可以幫助您追蹤爲什麼您的模型綁定器未被使用。

相關問題