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

后端 未结 9 1635
北荒
北荒 2020-11-29 08:03

I\'m following [Getting started with ASP.NET MVC 3][1]. And I can\'t add/edit with value of Price = 9.99 or 9,99. It said: \"The value \'9.99\' is not valid for Price.\" and

9条回答
  •  天命终不由人
    2020-11-29 08:40

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

提交回复
热议问题