简体   繁体   English

使用JQuery手风琴进行MVC验证

[英]MVC Validation with JQuery Accordion

I am relatively new to ASP.NET MVC but am really impressed by the validation features. 我对ASP.NET MVC相对较新,但其验证功能确实给我留下了深刻的印象。 I have a giant form that I have split into an accordion using JQuery UI. 我有一个巨大的表格,已使用JQuery UI拆分为手风琴。 This form is a very basic scaffold of a model and that model has code like the following to validate each field that is required: 此表单是模型的非常基本的框架,该模型具有如下代码以验证所需的每个字段:

    [Required(ErrorMessage="Please Enter a Valid Product")]
    [DisplayFormat(ConvertEmptyStringToNull= false)]
    [StringLength(160, MinimumLength=2,ErrorMessage="Product Must Be At Least 2 Characters")]

and then the view simply has: 然后视图仅具有:

            <div class="editor-label">
                @Html.LabelFor(model => model.Product)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Product)
                @Html.ValidationMessageFor(model => model.Product)
            </div>

That works great if that field is being viewed in the accordion. 如果正在手风琴中查看该字段,则效果很好。 If you leave the field blank, the messages shows up and everything works as planned. 如果将该字段保留为空白,则会显示消息,并且一切按计划进行。 Problem is, when I switch to a different tab in the accordion, and the required field isn't visible, I can submit the form just fine, much to the dismay of my server. 问题是,当我在手风琴中切换到另一个选项卡,并且必填字段不可见时,我可以提交表单就好了,这极大地困扰了我的服务器。 If I fill out the field, it is passed as expected of course. 如果我填写该字段,则按预期通过。 Is there a way to get around this? 有办法解决这个问题吗?

Turns out the answer was to put the following into the view: 原来的答案是将以下内容放入视图中:

$('#Form').validate().settings.ignore = []

The issue was that hidden fields are not checked using Jquery validation (which is what MVC uses) and once an accordian collapses they are hidden. 问题在于,未使用Jquery验证(这是MVC所使用的)检查隐藏字段,并且一旦折叠折叠,它们就会被隐藏。 This tells them not to ignore them. 这告诉他们不要忽略它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM