Asp.net-Mvc

ASP.NET MVC - 能夠處理數組的自定義模型綁定器

  • March 19, 2010

我需要實現一個功能,允許使用者以任何形式輸入價格,即允許 10 美元,10 $ , $ 10,… 作為輸入。

我想通過為 Price 類實現一個自定義模型綁定器來解決這個問題。

class Price { decimal Value; int ID; } 

表單包含一個數組或價格作為鍵

keys:
"Prices[0].Value"
"Prices[0].ID"
"Prices[1].Value"
"Prices[1].ID"
...

ViewModel 包含一個價格屬性:

public List<Price> Prices { get; set; }

只要使用者在 Value 輸入中輸入可轉換為十進制的字元串,預設模型綁定器就可以很好地工作。我想允許像“100 USD”這樣的輸入。

到目前為止,我的價格類型的 ModelBinder:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
   Price res = new Price();
   var form = controllerContext.HttpContext.Request.Form;
   string valueInput = ["Prices[0].Value"]; //how to determine which index I am processing?
   res.Value = ParseInput(valueInput) 

   return res;
}

如何實現正確處理數組的自定義模型 Binder?

明白了:關鍵是不要嘗試綁定單個 Price 實例,而是為List<Price>類型實現 ModelBinder:

   public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   {
       List<Price> res = new List<Price>();
       var form = controllerContext.HttpContext.Request.Form;
       int i = 0;
       while (!string.IsNullOrEmpty(form["Prices[" + i + "].PricingTypeID"]))
       {
           var p = new Price();
           p.Value = Process(form["Prices[" + i + "].Value"]);
           p.PricingTypeID = int.Parse(form["Prices[" + i + "].PricingTypeID"]);
           res.Add(p);
           i++;
       }

       return res;
   }

//register for List<Price>
ModelBinders.Binders[typeof(List<Price>)] = new PriceModelBinder();

引用自:https://stackoverflow.com/questions/2350689