本文介绍了ASP.NET MVC - 能够处理数组的自定义模型绑定器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个功能来允许用户以任何形式输入价格,即允许 10 美元、10 美元、10 美元...作为输入.

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.

我想通过为 Price 类实现自定义模型绑定器来解决这个问题.

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"
...

ViewModel 包含 Prices 属性:

The ViewModel contains a Prices property:

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

只要用户在 Value 输入中输入一个可转换的十进制字符串,默认模型绑定器就可以很好地工作.我想允许像100 美元"这样的输入.

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".

到目前为止,我的价格类型的 ModelBinder:

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;
}

如何实现正确处理数组的自定义模型 Binder?

How do I implement a custom model Binder that handles the arrays correctly?

推荐答案

明白了:重点是不要尝试绑定单个 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:

    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 MVC - 能够处理数组的自定义模型绑定器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 18:26