巴西真实的货币 - MVC / DataAnnotation

时间:2016-05-18 22:06:33

标签: c# asp.net-mvc entity-framework data-annotations

我需要实现货币输入,其中属性类型需要为decimal或double,并接受格式“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; }

EditorTemplate

@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.config culture =“pt-BR”。 问题是输入只接受“123,98”之类的值,如果我输入“1.123,98”,我会收到错误消息“值'9.999,99'对Salario无效。” 有没有办法让它允许点和逗号?我不想使用System.String。

更新 - 解决方案

我终于找到了解决方案!这是我的最终代码:

EditorTemplate

@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);
    }
}

Global.asax中

ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
ModelBinders.Binders.Add(typeof(double?), new DoubleModelBinder());

此自定义模型绑定器用于在将值发送到控制器之前格式化该值。我在这篇文章中找到了解决方案:Accept comma and dot as decimal separator

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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