Problem with double values binding

后端 未结 1 415
感动是毒
感动是毒 2020-12-17 23:45

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

相关标签:
1条回答
  • 2020-12-18 00:21

    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());
    
    0 讨论(0)
提交回复
热议问题