【问题标题】:Cannot validate null values for integer input in ASP.NET MVC?无法验证 ASP.NET MVC 中整数输入的空值?
【发布时间】: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" })。永远不要尝试设置namevalue 属性(并且无论如何都使用name = "Score" 不执行任何操作)并且助手已经在创建id="Score"
  • 感谢您的回复。你有什么建议来解决这个问题?我将整数输入用作第二个组件,当它为空时,我想验证并显示相关的错误消息。有什么帮助吗?
  • 为什么不使用TextBoxFor() 方法?
  • 什么意思?你的财产是int@Html.TextBoxFor(m =&gt; m.Score) 将创建与手动 html 相同的 html,除了它还将添加必要的 data-val-* 属性以进行客户端验证(以及为您提供手动 html 不会的正确 2 路模型绑定)
  • 注意最好使用$('#Score').TouchSpin({ ... });

标签: jquery asp.net-mvc validation integer data-annotations


【解决方案1】:

尝试将属性的类型从 int 更改为 int?

【讨论】:

  • 不能为空。
猜你喜欢
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 2013-05-31
  • 1970-01-01
相关资源
最近更新 更多