Accept comma and dot as decimal separator

artvolk picture artvolk · Jan 18, 2013 · Viewed 38.8k times · Source

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?

Answer

mathieu picture mathieu · Jan 18, 2013

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