我需要实现一种功能,允许用户以任何形式输入价格,即允许10美元,10美元,10美元……作为输入.
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; }
只要用户在Value输入中输入十进制可转换字符串,默认模型绑定器就可以正常工作.
我想允许输入“100美元”.
我的ModelBinder for Price类型到目前为止:
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();