error with decimal in mvc3 – the value is not valid for field

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());

Leave a Comment