加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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输入中输入十进制可转换字符串,默认模型绑定器就可以正常工作.
我想允许输入“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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读