【发布时间】:2016-09-24 22:55:51
【问题描述】:
如何在 ASP.NET MVC 中使用 DataAnnotations 验证 Score 属性?
[Required(ErrorMessage = "Required field")]
public int Score { get; set; }
我可以使用@Html.TextBoxFor 来验证这个字段:
@Html.TextBoxFor(m => m.Score, new { name = "Score", id = "Score",
@class = "form-control" , @Value = "" })
但无法验证整数输入:
<input type="text" id="Score" name="Score" value="" >
<script>
$("input[name='Score']").TouchSpin({
verticalbuttons: true
});
</script>
【问题讨论】:
-
您的手动代码没有生成必要的
data-val-* attributes for client side validation. And it shoould be@Html.TextBoxFor(m => m.Score, new { @class= "form-control" })。永远不要尝试设置name或value属性(并且无论如何都使用name = "Score"不执行任何操作)并且助手已经在创建id="Score" -
感谢您的回复。你有什么建议来解决这个问题?我将整数输入用作第二个组件,当它为空时,我想验证并显示相关的错误消息。有什么帮助吗?
-
为什么不使用
TextBoxFor()方法? -
什么意思?你的财产是
int!@Html.TextBoxFor(m => m.Score)将创建与手动 html 相同的 html,除了它还将添加必要的data-val-*属性以进行客户端验证(以及为您提供手动 html 不会的正确 2 路模型绑定) -
注意最好使用
$('#Score').TouchSpin({ ... });
标签: jquery asp.net-mvc validation integer data-annotations