【问题标题】:Currency for brazilian real - MVC/DataAnnotation巴西雷亚尔货币 - MVC/DataAnnotation
【发布时间】: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


【解决方案1】:

这个问题之前已经回答过了 看看Currency Formatting MVC 那个Darin Dimitrov 提供了。 关键是使用 DisplayFormat 注释的字段的 DataAnnotation

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]

【讨论】:

  • 如果您认为它是重复的,则将其标记为这样。但这与 OP 的问题无关(与验证有关)
猜你喜欢
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多