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

后端 未结 9 1649
北荒
北荒 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:36

    I've adapted the code from Leniel Macaferi a little bit so you can use it for any type:

    public class RequestModelBinder : 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
                {
                    // values really should be invariant
                    actualValue = Convert.ChangeType(valueResult.AttemptedValue, typeof(TBinding), CultureInfo.CurrentCulture);
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }
            }
    
            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
    
            return actualValue;
        }
    }
    

提交回复
热议问题