ValidationMessageFor的用法

时间:2014-12-19 19:48:43

标签: c# jquery asp.net-mvc asp.net-mvc-4 fluentvalidation

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

以下是我拥有的模型属性  的 m.CommunicationView.MobilePhone.Area  m.CommunicationView.MobilePhone.Number

 <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>

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

听起来像是在谈论客户端验证。每个字段都在其自身上进行验证,因此如果它有错误,您将收到错误消息。没有考虑其他字段是否也有错误消息。来自jQuery验证文档:

  

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

因此,只要该字段未以某种方式激活,就不会显示任何错误消息,但如果它已被激活且有错误,则会显示该消息。同样,这是逐场的。但是,如果问题在于它弄乱了用户界面,那么你应该修改你的用户界面来容纳这些消息。 良好的用户界面可以告知用户所有潜在的问题,因此他们不会在无休止的提交和尝试再次循环中浪费时间。

此外,您将获得与服务器端验证相同的功能,因为当模型错误返回视图时,将显示所有字段的所有错误。最好接受这一点,让你的用户界面更加适应。

答案 2 :(得分:1)

您需要包含正确的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具有此功能(Root web.config,而不是views / web.config)将其放在appSettings节点中

<add key="UnobtrusiveJavaScriptEnabled" value="true" />
相关问题