参见英文答案 >
How to set decimal separators in ASP.NET MVC controllers?4个答案ASP.NET MVC中的模型绑定很棒,但它遵循区域设置。在我的语言环境中,小数点分隔符是逗号(‘,’),但用户也使用点(‘。’),因为它们懒得切换布局。我希望在我的模型中的所有十进制字段的一个地方实现。
我应该为十进制类型实现自己的Value Provider(或事件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()中注册它:
ModelBinders.Binders.Add(typeof(decimal),new DecimalModelBinder()); ModelBinders.Binders.Add(typeof(decimal?),new DecimalModelBinder());
积分:Default ASP.NET MVC 3 model binder doesn’t bind decimal properties
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。