【问题标题】:MVC 4 TextBoxFor HTML5 CurrencyMVC 4 TextBoxFor HTML5 Currency
【发布时间】:2014-07-04 18:15:53
【问题描述】:

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

有人可以演示我如何修改下面的代码以确保只能在表单中输入带小数点和 2 位小数的真实价格。

还可以在字段前加上 £ (&pound) 字符,但显然在 post 提交的值中省略了 £ 符号?

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" })

【问题讨论】:

  • 你在使用 Bootstrap 吗?如果是这样,我会将货币符号保留在文本框中,并使用 Bootstrap 输入组getbootstrap.com/components/#input-groups-basic
  • 你可以试试 Html.EditorFor
  • 我确实在使用 Boostrap。
  • 如果我使用@Html.EditorFor(m => m.Amount, new { @class = "form-control", placeholder = "Amount", required = "required" }),css 类不适用。
  • 不能给EditorFor添加类,如果由于某种原因需要添加类,请改用TextBoxFor。

标签: c# html asp.net-mvc-4


【解决方案1】:

我最终使用了以下符合 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" })

这似乎成功了:-)

【讨论】:

    【解决方案2】:

    用正则表达式装饰属性。 另外我注意到您希望在视图控件中发出 Requiered 属性,但最佳做法是在您的实体中执行此操作,因此最终装饰可能如下所示:

    [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 建议的方式进行

    【讨论】:

      猜你喜欢
      • 2011-06-18
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多