Reputation: 59
I wrote an application with model validation, but when i try to enter decimal values i'm getting
The value '12.12' is not valid for Price.
[Required(ErrorMessage = "Price is required.")]
[Range(0, 9999.99)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
Upvotes: 2
Views: 1581
Reputation: 3483
in dotnet core mvc 5 and above you can set 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);
Upvotes: 1
Reputation: 308
I just stumbled on this again after 2 years. I thought ASP.NET MVC 5 had solved this but looks like it's not the case. So here goes how to solve the problem.
Create a class called DecimalModelBinder like the following and add it to the root of your project for example:
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;
}
}
}
Inside Global.asax.cs, make use of it in Application_Start()
like this:
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
Upvotes: 3
Reputation: 59
ok, so i added in my Startup.cs
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("en-US");
});
and
app.UseRequestLocalization();
and it worked
Upvotes: 2