Custom Model Binder for decimals and integer: How to get the string value before MVC and do a smarter conversion

前端 未结 3 1141
时光说笑
时光说笑 2021-01-20 04:54

I want to extend the default model binding to be more smart when dealing with numbers. The default works very bad when are commas and decimals points in the game.

I

3条回答
  •  不思量自难忘°
    2021-01-20 05:00

    What about this?

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

    And a custom binder. I guess I don't know if you can override decimal binding in this way, but it works for my own types.

    public class DecimalModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult == null)
            {
                return base.BindModel(controllerContext, bindingContext);
            }
            // to-do: your parsing (get the text value from valueProviderResult.AttemptedValue)
            return parsedDecimal;
        }
    }
    

提交回复
热议问题