C# mvc 5 数据批注限制小数点后的数字

本文关键字:小数点 数字 mvc 数据 | 更新日期: 2024-12-05 17:30:00

我有这样的模型

public class Invoice
{
    int  Invoice Number{get;set;}
    [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = false)]
    public float ReceivedAmount { get; set; }
}

在视图页面中,ReceivedAmount接受点喜欢之后的许多数字500.25251,但我想要 500.25

它应该阻止在字段中输入值。不显示错误消息

C# mvc 5 数据批注限制小数点后的数字

接受输入与[DisplayFormat()]无关,如果您愿意,您仍然可以添加,但事实并非如此。你需要的是一个[RegularExpression()]

[RegularExpression(@"^'d+.'d{0,2}$",ErrorMessage = "Price can't have more than 2 decimal places")]
public float ReceivedAmount { get; set; }
正则表达式

属性类:指定动态数据中的数据字段值必须与指定的正则表达式匹配 ASP.NET。

[RegularExpression(@"^[0-9]+('.[0-9]{1,2})?$",ErrorMessage = "The Price cannot exceed 2 decimal places. Please Re-enter")]
public float ReceivedAmount { get; set; }

使用以下代码:

   [DisplayFormat(DataFormatString="{0:#.##}")]
   public float ReceivedAmount { get; set; }