7

我需要實現一個功能,允許用戶以任何形式輸入價格,即允許10美元,10美元,10美元...作爲輸入。ASP.NET MVC - 自定義模型綁定器能夠處理陣列

我想通過爲Price類實現自定義模型聯編程序來解決此問題。

class Price { decimal Value; int ID; } 

的形式包含一個數組或價格作爲鍵

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

的視圖模型包含價格屬性:

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

默認模型粘合劑很好地工作,只要該用戶輸入一個十進制可轉換字符串到值輸入中。 我希望允許像「100美元」這樣的輸入。

我迄今價格類型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; 
} 

如何實現正確處理的數組中的自定義模型活頁夾?

+0

難道我猜對了那個ID是用戶ID和不是ID貨幣? – AxelEckenberger

+0

這是定價類型的編號,與此問題無關 – Marek

+0

不需要多種貨幣 - 我們固定爲單一貨幣,但需要允許各種輸入格式,如問題 – Marek

回答

16

明白了:問題的關鍵是不要嘗試結合單一價格實例,而是實現ModelBinder的用於List<Price>類型:

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();