C# 无效的十进制验证
我编写了一个带有模型验证的应用程序,但当我尝试输入十进制值时,我得到了 值“12.12”对价格无效C# 无效的十进制验证,c#,validation,asp.net-core,C#,Validation,Asp.net Core,我编写了一个带有模型验证的应用程序,但当我尝试输入十进制值时,我得到了 值“12.12”对价格无效 两年后我又一次偶然发现了这一点。我以为ASP.NETMVC5已经解决了这个问题,但看起来情况并非如此。因此,如何解决这个问题 创建一个名为DecimalModelBinder的类,如下所示,并将其添加到项目的根目录中,例如: using System; using System.Globalization; using System.Web.Mvc; namespace YourNamespac
两年后我又一次偶然发现了这一点。我以为ASP.NETMVC5已经解决了这个问题,但看起来情况并非如此。因此,如何解决这个问题 创建一个名为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\u Start()
中使用它,如下所示:
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
两年后我又一次偶然发现了这一点。我以为ASP.NETMVC5已经解决了这个问题,但看起来情况并非如此。因此,如何解决这个问题 创建一个名为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\u Start()
中使用它,如下所示:
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
好的,我在Startup.cs中添加了
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("en-US");
});
它工作正常,所以我在Startup.cs中添加了
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("en-US");
});
它成功了你的文化是什么?我试图添加到web.config,但仍然收到相同的错误你的文化是什么?我试图添加到web.config,但仍然收到相同的错误