asp.net-mvc – ASP.NET MVC – 能够处理数组的自定义模型绑定器
发布时间:2020-12-15 22:21:02 所属栏目:asp.Net 来源:网络整理
导读:我需要实现一种功能,允许用户以任何形式输入价格,即允许10美元,10美元,10美元……作为输入. 我想通过为Price类实现自定义模型绑定器来解决这个问题. class Price { decimal Value; int ID; } 表单包含一个数组或价格作为键 keys:"Prices[0].Value""Prices[0]
我需要实现一种功能,允许用户以任何形式输入价格,即允许10美元,10美元,10美元……作为输入.
我想通过为Price类实现自定义模型绑定器来解决这个问题. class Price { decimal Value; int ID; } 表单包含一个数组或价格作为键 keys: "Prices[0].Value" "Prices[0].ID" "Prices[1].Value" "Prices[1].ID" ... ViewModel包含一个Price属性: public List<Price> Prices { get; set; } 只要用户在Value输入中输入十进制可转换字符串,默认模型绑定器就可以正常工作. 我的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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.NET总结
- asp.net-mvc – 如何在使用Razor图表助手创建的图表中更改图
- asp.net-mvc-3 – 模型绑定逗号分隔的查询字符串参数
- asp.net-mvc – 无法导出Kendo Grid中的隐藏列
- asp.net – 配置示例
- asp.net-mvc – 服务txt的asp.net mvc被截断
- .NET Core的文件系统[3]:由PhysicalFileProvider构建的物理
- asp.net – 如何防止低效的SQL查询减慢数据库服务器的速度
- asp.net-mvc – 根据请求域捆绑CSS文件?
- asp.net-mvc-4 – Azure上的PushSharp ASP.net MVC4问题. –
推荐文章
站长推荐
- 如何在ASP.Net中设置Page.IsValid
- asp.net – 如何在codebehind中更新dotnetnuke u
- asp.net-mvc – 如何在ASP.Net MVC中的EditorTem
- asp.net – 如何发布站点从命令行与一些发布配置
- asp.net-identity – UseOAuthBearerTokens vs U
- asp.net – 为jQuery寻找一个好的数据网格插件
- asp.net-mvc – 为什么InitializeSimpleMembersh
- Asp.net下使用Jquery Ajax传送和接收DataTable的
- 接受List的ASP.NET Web方法失败,“Web服务方法名
- asp.net – 干净的方式来防止输入按钮提交表单
热点阅读