Usage of ValidationMessageFor

本文关键字:ValidationMessageFor of Usage | 更新日期: 2023-09-27 18:34:54

如何检查模型属性是否存在验证错误 - 我正在使用验证消息方法来显示错误消息。如何一次只显示一条错误消息?我

这是我拥有的模型属性 m.通信视图.手机.区域 m.通信视图.手机.号码

 <div class="fl">
   @Html.TextBoxFor(m => m.CommunicationView.MobilePhone.Area, new { @id = "personalDetailMobilePhoneAreaInput",  @class="customText wdt80 numericValue",type = "text",maxlength="2" })
   @Html.TextBoxFor(m => m.CommunicationView.MobilePhone.Number, new { @id = "personalDetailMobilePhoneNumberInput",  @class="customText wdt120 mrglft10 phnIE numericValue",type = "text",maxlength="8" })
   @Html.ValidationMessageFor(m => m.CommunicationView.MobilePhone.Area)
   @Html.ValidationMessageFor(m => m.CommunicationView.MobilePhone.Number)
</div>

Usage of ValidationMessageFor

只需将ErrorMessage字段添加为模型中[Required]装饰器的一部分即可。例如对于数字:

[Required(ErrorMessage = "Number is required")]
[StringLength(10, ErrorMessage = "Number can be no larger than 10 characters")]
public string Number { get; set; }

听起来你在谈论客户端验证。每个字段都经过单独验证,因此如果它有错误,您将收到一条错误消息。不考虑其他字段是否也有错误消息。来自 jQuery 验证文档:

默认情况下,表单在提交时

进行验证,由用户单击提交按钮或在表单输入聚焦时按 Enter 触发(提交时选项(。此外,一旦某个字段被突出显示为无效,每当用户在该字段中键入内容(选项 onkeyup(时,就会对其进行验证。当用户在有效字段中输入无效内容时,当字段失去焦点时也会对其进行验证(选项 onblur(。(强调我的(

因此,只要该字段尚未以某种方式激活,就不会出现错误消息,但如果它已被激活并且有错误,则会出现该消息。同样,这是逐个领域的基础。但是,如果问题是它"弄乱了 UI",您可能应该只修复您的 UI 以适应消息。一个好的 UI 会通知用户所有潜在的问题,这样他们就不会在无休止的提交和重试循环中浪费时间。

此外,服务器端验证也是如此,因为当由于模型错误而返回视图时,将显示所有字段的所有错误。最好只是接受这一点,让你的UI更适应。

您需要包含正确的 jquery 库,这些库会在文本框/控件失去焦点时自动显示错误。将它们放在布局页面中。

    @Scripts.Render("~/bundles/jqueryval")
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>  

确保在对 jquery 库的主调用之后调用它们。还要确保在 AppStart/BundleConfig 中设置了捆绑包.cs

  bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));  

最后,确保你的 webconfig 有这个(根 web.config,而不是 views/web.config(把它放在你的 appSettings 节点中

<add key="UnobtrusiveJavaScriptEnabled" value="true" />
相关文章:
  • 没有找到相关文章