Standard ASP.NET MVC 3 Model Binding Does Not Bind Decimal Properties

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

{"BaseLoanAmount": 5000} 

which is supposedly associated with a model with a decimal property named "BaseLoanAmount", it does not bind, it just remains 0. But if I send:

 {"BaseLoanAmount": 5000.00} 

it binds a property, but why? Can't convert 5000 to decimal if it doesn't have decimal numbers?

+46
asp.net-mvc-3
Apr 18 '11 at 5:45 a.m.
source share
2 answers

After going to asp.net mvc source code, the problem seems to be that for converting asp.net mvc uses a framework type converter that for some reason returns false to convert int to decimal conversion, I ended up using a binder provider custom and model binder for decimal places, you can see 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, simply enter the following line inside Application_Start() :

 ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder()); 
+71
Apr 22 '11 at 20:32
source share

Try sending it as follows:

 { "BaseLoanAmount": "5000" } 
+12
Apr 18 2018-11-11T00:
source share



All Articles