8

In my project I want to allow users input double values in 2 formats: with using ',' or '.' as delimiter (I'm not interested in exponential form). By default value with delimiter '.' don't work. I want this behavior works for all double properties in complex model objects (currently I work with collections of objects, that contains identifiers and values).

What i should use: Value Providers or Model Binders? Please, show code example of solving my problem.

David Levin
  • 6,573
  • 5
  • 48
  • 80
  • 2
    http://stackoverflow.com/questions/5050641/asp-net-mvc-model-binder-with-global-number-formats help at all? –  Jun 29 '11 at 11:53

1 Answers1

19

You could use a custom model binder:

public class DoubleModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (result != null && !string.IsNullOrEmpty(result.AttemptedValue))
        {
            if (bindingContext.ModelType == typeof(double))
            {
                double temp;
                var attempted = result.AttemptedValue.Replace(",", ".");
                if (double.TryParse(
                    attempted,
                    NumberStyles.Number,
                    CultureInfo.InvariantCulture,
                    out temp)
                )
                {
                    return temp;
                }
            }
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

which could be registered in Application_Start:

ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thank you for clear answer, but what is the purpose of Value Providers? Is it abstraction over different sources (like form value collection, url parameters, server variables, cookies etc.)? – David Levin Jun 30 '11 at 17:38
  • Plus, don't forget to add same binder for Nullable type – vasilyk Sep 23 '17 at 21:46