MVC 4 TextBoxFor HTML5 Currency

本文关键字:Currency HTML5 TextBoxFor MVC | 更新日期: 2023-09-27 18:11:04

我试图在文本框中输入带有小数点的数字,但我得到错误You must enter a valid value

谁能演示一下我如何修改下面的代码,以确保只有小数点和小数点后两位的真实价格才能输入到表单中。

也有可能在字段的前缀加上一个£(£字符,但显然在提交的值中省略了£符号?

Test.cs

[DisplayName("Amount")]
public Decimal Amount { get; set; }

Index.cshtml

@Html.TextBoxFor(m => m.Amount, new { @class = "form-control", type = "number", placeholder = "Amount", required = "required" })

MVC 4 TextBoxFor HTML5 Currency

我最终使用了以下HTML5兼容的代码:

Test.cs

[Required]
[DisplayName("Amount")]
[Range(0.01, 100000.00)]
public Decimal Amount { get; set; }

Index.cshtml

@Html.TextBoxFor(m => m.Amount, new { @class = "form-control", type = "number", step = "0.01", max = "100000.00", placeholder = "Amount", required = "required" })

这个似乎成功了:-)

用regulareexpression装饰属性。另外,我注意到你想要在视图控件中发出required属性,但最好在你的实体中这样做,所以最终装饰可能看起来像这样:

[Requiered,RegularExpression(@"^'d+.'d{0,2}$", ErrorMessage = "Amount must be a number with two decimal place")]
public Decimal Amount { get; set; }

…并在视图中使用EditorFor

@Html.EditorFor(model => Model.Peso)

对于货币符号,我将按照@DavidG建议的方式