ASP.NET MVC模型绑定器忽略逗号小数分隔符

时间:2016-04-06 14:36:09

标签: c# asp.net-mvc

来自http请求的120,12在双模型中被转换为12012。我读过ASP.NET MVC应该处理这些事情,但我无法使其工作

请求:

Accept-Language:da,en;q=0.8,ru;q=0.6,en-US;q=0.4
...
Price: "120,12"

动作方法'模型包含:public double Price { get; set; }

内幕:

var uICulture = Thread.CurrentThread.CurrentUICulture; // {da}
var culture = Thread.CurrentThread.CurrentCulture; // {da-DK}

本地化由Global.asax内的Application_AcquireRequestState控制:

var cultureInfo = new CultureInfo("da"); 
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以编写自定义模型装订器。

    public class DecimalModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);
            var modelState = new ModelState {Value = valueResult};
            object actualValue = null;
            try
            {
                //Check if this is a nullable decimal and a null or empty string has been passed
                var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
                                          string.IsNullOrEmpty(valueResult.AttemptedValue));

                //If not nullable and null then we should try and parse the decimal
                if (!isNullableAndNull)
                {
                    actualValue = decimal.Parse(valueResult.AttemptedValue, NumberStyles.Any, CultureInfo.CurrentCulture);
                }
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
    }
}

只需将CultureInfo.CurrentCulture更改为用户在decimal.Parse语句中选择的文化。然后在启动时注册新的模型绑定器。