【问题标题】:DataType.Currency unobtrusive validation not workingDataType.Currency 不显眼的验证不起作用
【发布时间】:2013-01-08 14:14:18
【问题描述】:

此代码不起作用,有人可以帮助我吗?

型号:

    [Display(ResourceType = typeof(HeelpResources), Name = "AdViewModel_Price_Label")]
    [Required(ErrorMessageResourceName = "ErrorMsgRequiredField", ErrorMessageResourceType = typeof(HeelpResources))]
    [DataType(DataType.Currency, ErrorMessageResourceName = "ErrorMsgPriceFormat", ErrorMessageResourceType = typeof(HeelpResources))]
    public decimal Price { get; set; }

在客户端生成这个:

data-val-number="The field Preço: must be a number".

而不是应该在资源“ErrorMsgPriceFormat”中的消息。

谢谢。

【问题讨论】:

  • 您如何将数据输入到input 字段中?
  • 嗨,在葡萄牙,货币格式为 2.000,00,我想接受格式 2000,00 - 现在我有正则表达式:RegularExpression(@"^\d+(\, \d{1,2})?$")

标签: c# jquery model-view-controller asp.net-mvc-4 data-annotations


【解决方案1】:

我很确定您将要做的更多是这些方面的事情:

public string FormattedPrice { get; set; }

使用您提供的 RegEx 进行装饰,以确保他们输入有效的货币值并将 input 绑定到该字段。

然后,当你开始行动时,你会想要用Decimal.TryParse 做这样的事情:

decimal result;
var success = decimal.TryParse(o.FormattedPrice, NumberStyles.AllowDecimalPoint, CultureInfo.DefaultThreadCurrentCulture, out result);

其中o 是发布到操作的模型实例。此外,NumberStyles.AllowDecimalPoint 应转换为 ,,就像在您的示例中那样,因为您的文化。我知道这有点倒退,但是这样想,在美国,小数点分隔符是 .,所以对于您的文化,相同的枚举值转换为 ,

如果解析成功,则success 为真,您可以将result 设置为o.Price

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2011-10-18
    • 1970-01-01
    相关资源
    最近更新 更多