Default ASP.NET MVC 3 model binder doesn't bind decimal properties

前端 未结 2 861
醉梦人生
醉梦人生 2020-11-29 21:37

For some reason, when I send this JSON to an action:

{\"BaseLoanAmount\": 5000}

which is supposed to be bound to a model with a decimal pro

相关标签:
2条回答
  • 2020-11-29 22:06

    Try sending it like this:

    { "BaseLoanAmount": "5000" }
    
    0 讨论(0)
  • 2020-11-29 22:21

    After stepping into asp.net mvc's source code, it seemsd the problem is that for the conversion asp.net mvc uses the framework's type converter, which for some reason returns false for an int to decimal conversion, I ended up using a custom model binder provider and model binder for decimals, you can see it here:

    public class DecimalModelBinder : DefaultModelBinder
    {
        #region Implementation of IModelBinder
    
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    
            if (valueProviderResult.AttemptedValue.Equals("N.aN") ||
                valueProviderResult.AttemptedValue.Equals("NaN") ||
                valueProviderResult.AttemptedValue.Equals("Infini.ty") ||
                valueProviderResult.AttemptedValue.Equals("Infinity") ||
                string.IsNullOrEmpty(valueProviderResult.AttemptedValue))
                return 0m;
    
           return Convert.ToDecimal(valueProviderResult.AttemptedValue);
        }    
    
        #endregion
    }
    

    To register this ModelBinder, just put the following line inside Application_Start():

    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
    
    0 讨论(0)
提交回复
热议问题