我编写了一个带有模型验证的应用程序,但是当我尝试输入十进制值时,我得到了
“12.12”值对Price无效。
[Required(ErrorMessage = "Price is required.")]
[Range(0, 9999.99)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }发布于 2018-06-06 10:10:15
两年后我又偶然发现了这个。我以为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());发布于 2018-06-06 10:29:52
好吧,所以我加入了我的Startup.cs
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("en-US");
});和
app.UseRequestLocalization();而且它起作用了
发布于 2021-11-28 15:18:03
在dotnet核心mvc 5及以上版本中,您可以设置NumberDecimalSeparator="."
var supportedCultures = new[] { "ar", "es" };
var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
localizationOptions.DefaultRequestCulture.Culture.NumberFormat.NumberDecimalSeparator=".";
app.UseRequestLocalization(localizationOptions);https://stackoverflow.com/questions/50717452
复制相似问题