接受逗号和点作为小数分隔符

art*_*olk 22 asp.net-mvc modelbinders value-provider

ASP.NET MVC中的模型绑定很棒,但它遵循区域设置.在我的语言环境中,小数点分隔符是逗号(','),但用户也使用点('.'),因为它们懒得切换布局.我想在一个地方为decimal我的模型中的所有字段实现这个.

我应该为decimal类型实现自己的Value Provider(或事件Model Binder),还是我错过了一些简单的方法来做到这一点?

mat*_*ieu 38

最干净的方法是实现自己的模型绑定器

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
    }    
}
Run Code Online (Sandbox Code Playgroud)

并在Application_Start()中注册它:

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
Run Code Online (Sandbox Code Playgroud)

致谢:默认ASP.NET MVC 3模型绑定器不绑定小数属性


Mig*_*oso 5

要正确处理组分隔符,只需替换

Convert.ToDecimal(valueProviderResult.AttemptedValue);
Run Code Online (Sandbox Code Playgroud)

在选定的答案中

Decimal.Parse(valueProviderResult.AttemptedValue, NumberStyles.Currency);
Run Code Online (Sandbox Code Playgroud)

  • 或NumberStyles.Any,如果你想狂奔. (2认同)