首页 > 解决方案 > 无效的十进制验证

问题描述

我编写了一个带有模型验证的应用程序,但是当我尝试输入十进制值时,我得到了

值“12.12”对价格无效。

[Required(ErrorMessage = "Price is required.")]
[Range(0, 9999.99)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

标签: c#validationasp.net-core

解决方案


2年后,我再次偶然发现了这一点。我以为 ASP.NET MVC 5 已经解决了这个问题,但看起来情况并非如此。所以这里是如何解决这个问题的。

创建一个名为 DecimalModelBinder 的类,如下所示,并将其添加到项目的根目录,例如:

using System;
using System.Globalization;
using System.Web.Mvc;

namespace YourNamespace
{   
    public class DecimalModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            ModelState modelState = new ModelState { Value = valueResult };

            object actualValue = null;

            if(valueResult.AttemptedValue != string.Empty)
            {
                try
                {
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
                }
                catch(FormatException e)
                {
                    modelState.Errors.Add(e);
                }
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);

            return actualValue;
        }
    }
}

在 Global.asax.cs 中,像这样使用它Application_Start()

ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

推荐阅读