asp.net-mvcmodelbindersvalue-provider

Accept comma and dot as decimal separator


Model binding in ASP.NET MVC is great, but it follows locale settings. In my locale decimal separator is comma (','), but users use dot ('.') too, because they are lazy to switch layouts. I want this implemented in one place for all decimal fields in my models.

Should I implement my own Value Provider (or event Model Binder) for decimal type or I've missed some simple way to do this?


Solution

  • Cleanest way is to implement your own model binder

    public class DecimalModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    
            return valueProviderResult == null ? base.BindModel(controllerContext, bindingContext) : Convert.ToDecimal(valueProviderResult.AttemptedValue);
            // of course replace with your custom conversion logic
        }    
    }
    

    And register it inside Application_Start():

    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
    

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