ASP.NET MVC - 能够处理数组的自定义模型绑定器
我需要实现一个功能,允许用户以任何形式输入价格,即允许 10 美元、10 美元、10 美元...作为输入。
我想通过为 Price 类实现自定义模型绑定器来解决这个问题。
class Price { decimal Value; int ID; }
表单包含一个数组或 Price 作为键
keys:
"Prices[0].Value"
"Prices[0].ID"
"Prices[1].Value"
"Prices[1].ID"
...
。 ViewModel 包含 Price 属性:
public List<Price> Prices { get; set; }
只要用户在 Value 输入中输入可十进制转换的字符串,默认模型绑定器就可以很好地工作。 我想允许输入“100 美元”之类的内容。
到目前为止,我的 Price 类型的 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?
I need to implement a functionality to allow users to enter price in any form, i.e. to allow 10 USD, 10$, $10,... as input.
I would like to solve this by implementing a custom model binder for Price class.
class Price { decimal Value; int ID; }
The form contains an array or Prices as keys
keys:
"Prices[0].Value"
"Prices[0].ID"
"Prices[1].Value"
"Prices[1].ID"
...
The ViewModel contains a Prices property:
public List<Price> Prices { get; set; }
The default model binder works nicely as long as the user enters a decimal-convertible string into the Value input.
I would like to allow inputs like "100 USD".
My ModelBinder for Price type so far:
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;
}
How do I implement a custom model Binder that handles the arrays correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
明白了:重点是不要尝试绑定单个 Price 实例,而是为
List
类型实现 ModelBinder:Got it: The point is to not try to bind a single Price instance, but rather implement a ModelBinder for
List<Price>
type: