ASP.NET MVC binding decimal value

后端 未结 4 2123
既然无缘
既然无缘 2021-01-04 00:19

I\'m trying to figure out why framework refuses to bind \"1,234.00\" value to decimal. What can be the reason for it?

Values like \"123.00\" or \"123.0000\" bind suc

4条回答
  •  渐次进展
    2021-01-04 01:06

    You can try overriding the DefaultModelBinder. Let me know if this doesn't work and I'll delete this post. I didn't actually put together an MVC app and test it, but based on experience this should work:

    public class CustomModelBinder : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            if(propertyDescriptor.PropertyType == typeof(decimal))
            {
                propertyDescriptor.SetValue(bindingContext.Model, double.Parse(propertyDescriptor.GetValue(bindingContext.Model).ToString()));
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
            else
            {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
        }
    }
    

提交回复
热议问题