error with decimal in mvc3 - the value is not valid for field
I encountered this issue when developing a web application for an English audience, on a Pc in The Netherlands.
A model property of type double, generated this server-side validation error:
The value '1.5' is not valid for .
On an breakpoint, I saw these values in the Immediate Window:
?System.Threading.Thread.CurrentThread.CurrentUICulture
{en-US}
?System.Threading.Thread.CurrentThread.CurrentCulture
{nl-NL}
As a solution (or maybe a work-around), you can specify the globalization settings in the web.config file.
<configuration>
<system.web>
<globalization culture="en" uiCulture="en" />
Of course this means that you force your users to enter numbers in English formatting, but that is just fine, in my case.
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());
You are one of the non-English customers, which MS has not foreseen. You will need to put some extra effort into making your version run. I had a similar problem, denying me both "9,99" and "9.99" as valid numbers. It seems like once server-side validation failed, and once client-side validation, causing no number to be accepted.
So you have to make the validation congruent.
Like suggested in the comments, have a look at http://msdn.microsoft.com/en-us/library/gg674880(VS.98).aspx and http://haacked.com/archive/2010/05/10/globalizing-mvc-validation.aspx and MVC 3 jQuery Validation/globalizing of number/decimal field or - should you understand German (or just look at the code examples) http://www.andreas-reiff.de/2012/06/probleme-mit-mvcmovies-beispiel-validierung-des-preises-mit-dezimalstellen-schlagt-fehl/
BTW, same problem exists for both the Music and Movie example tutorials.