cshtml TextBoxFor应该只接受数字(0-10)

时间:2016-02-18 09:13:09

标签: asp.net-mvc validation razor

我在表格中有一个文本框。即,

我必须只允许文本框中的数字,我想尝试如下。

但是,(+-.)符号在文本框中被接受(例如:" + 123"," -123& #34;," .123")虽然我正在做@type="number"

任何帮助都将不胜感激。

我的代码

<td>@Html.TextBoxFor(modelItem => item.Amount, new { @id = "amount", @type = "number"})</td>

1 个答案:

答案 0 :(得分:1)

您可以在这种情况下使用unobtrusivevalidation

添加脚本并更改Web.Config之后,您应该只注释您的模型属性:

public class YourViewModel
{
   [Range(typeof(int), "0", "10", ErrorMessage = "{0} can only be between {1} and {2}")]
   public int Amount { get; set; }
   /* other properties */
}

然后如果你这样写:

<td>@Html.TextBoxFor(x => x.Amount)</td>

Razor将通过客户端验证创建input

相关问题