簡體   English   中英

為什么我不能為列表注冊自定義模型活頁夾 <int> ?

[英]Why can't I register a custom model binder for a List<int>?

我有一個看起來像的動作

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

userId的列表可能會變得很長,因此我想使用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嗎?

在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類的 GetParameterValue方法

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

  3. 活頁夾已在ModelBinders.Binders詞典中全局注冊。

  4. [ModelBinder()]屬性中為模型類型定義的Binder。

  5. DefaultModelBinder。

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

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

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

希望這將幫助您找到未使用模型聯編程序的原因。

您是否嘗試過在action方法中使用ModelBinder屬性?

public ActionResult GetUsers([ModelBinder(typeof(JsonBinder))] List<int> userIds)

參考: https : //msdn.microsoft.com/zh-cn/library/system.web.mvc.modelbinderattribute(v= vs.118) .aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM