ASP.NET MVC - 自定义模型绑定能够处理的数组 [英] ASP.NET MVC - Custom model binder able to process arrays

查看:249
本文介绍了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.

我想实现一个自定义模型粘合剂价格类来解决这个问题。

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

默认的模型粘合剂,只要用户输入一个十进制转换串入值输入很好地工作。
我想,让喜欢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;
}

我如何实现一个自定义模型绑定正确处理数组?

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

推荐答案

明白了:关键是不要尝试绑​​定一个单一的价格实例,而是落实列表℃的ModelBinder的;价格&gt; 类型:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆