【发布时间】:2016-09-15 14:31:31
【问题描述】:
我需要实现货币输入,其中属性类型需要为十进制或双精度并接受格式“0.00,00”。
视图模型
[RegularExpression(@"^([1-9]{1}[\d]{0,2}(\.[\d]{3})*(\,[\d]{0,2})?|[1-9]{1}[\d]{0,}(\,[\d]{0,2})?|0(\,[\d]{0,2})?|(\,[\d]{1,2})?)$")]
public Decimal Salario { get; set; }
编辑器模板
@model Decimal?
@Html.TextBox("", Model.HasValue && Model.Value > 0 ? Model.Value.ToString() : "", new { @class = "form-control text-box single-line money" })
<script type="text/javascript">
$(document).ready(function () {
$(".money").maskMoney({ thousands: '.', decimal: ',', prefix: "" });
});
</script>
我还设置了我的 web.configculture="pt-BR"。 问题是输入只接受像“123,98”这样的值,如果我输入“1.123,98”,我会收到错误消息“值'9.999,99'对Salario无效。”。 有没有办法让它允许点和逗号?我不想使用 System.String。
更新 - 解决方案
我终于找到了解决办法!这是我的最终代码:
编辑器模板
@model Double?
@Html.TextBox("", Model.HasValue && Model.Value > 0 ? Model.Value.ToString() : "", new { @class = "form-control text-box single-line money" })
<script type="text/javascript">
$(document).ready(function () {
$(".money").maskMoney({ thousands: '.', decimal: ',', prefix: "R$ " });
});
</script>
视图模型
[DataType("Money")] //Money is the name of my EditorTemplate
public decimal Valor { get; set; }
自定义模型绑定器
public class DoubleModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return valueProviderResult != null && !string.IsNullOrEmpty(valueProviderResult.AttemptedValue) ? Convert.ToDouble(valueProviderResult.AttemptedValue.Replace("R$", "").Trim()) : base.BindModel(controllerContext, bindingContext);
}
}
全球.asax
ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
ModelBinders.Binders.Add(typeof(double?), new DoubleModelBinder());
此自定义模型绑定器用于在将值发送到控制器之前对其进行格式化。我在这篇文章中找到了解决方案:Accept comma and dot as decimal separator。
谢谢!
【问题讨论】:
-
脚本永远不应出现在
EditorTemplate中 - 将其移至主视图。您是在使用不显眼的客户端验证(即收到阻止您的表单提交的验证错误 - 在这种情况下您需要重新配置$.validator),还是在服务器上进行验证(在这种情况下,您的服务器文化是什么? ) -
作为评论,您可能应该将货币存储在最小的子单元中作为
int。
标签: c# asp.net-mvc entity-framework data-annotations