接受逗号和点作为小数点分隔符 [英] Accept comma and dot as decimal separator

查看:189
本文介绍了接受逗号和点作为小数点分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型的ASP.NET MVC结合是伟大的,但它遵循区域设置。在我的区域设置小数点分隔符是逗号(','),但用户使用点(。)也是如此,因为他们是懒惰的切换布局。我想这在一个地方实施了所有的小数在我的模型字段。

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?

推荐答案

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

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
    }    
}

和注册它里面的Application_Start():

And register it inside Application_Start():

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

学分:<一href=\"http://stackoverflow.com/questions/5698984/default-asp-net-mvc-3-model-binder-doesnt-bind-decimal-propeties\">Default ASP.NET MVC 3模型绑定犯规绑定小数化子性质

这篇关于接受逗号和点作为小数点分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆