I'm developing an ASP .NET MVC 5 application in Visual Studio 2015. I have a simple model created:
public class Article
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
and standard, Visual Studio-added controller and a view. Of course I have a problem with Price decimal field. While trying to add/edit an existing Article, when I type decimal as for instance 5,45
I got an validation error The field Price must be a number.
. If I type it as 5.45
I don't get this error, however after submitting the form in my controller Price
property of the Article is set to 0 all the time.
I explored the web and forums and according to this post's answer created the model binder for decimals as:
public class DecimalModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return valueProviderResult == null ? base.BindModel(controllerContext, bindingContext) : Convert.ToDecimal(valueProviderResult.AttemptedValue);
}
}
and then in my Global.asax.cs
file I put two lines to add this binder for decimals
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
FluentValidationModelValidatorProvider.Configure();
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
}
However, I still have the same issues, nothing changed.
I also tried to enforce the culture of my PC by putting the following snippet into my Web.config
file (as advised in this tutorial):
<system.web>
<globalization culture ="en-US" />
<!--elements removed for clarity-->
but it's all the time the same issue :(. Can you please help me with that? I suppose I'm missing something, but I followed all possible solutions 10 times already and it's still the same...
Thank you in advance!