正在验证MVC隐藏字段

Sac*_*nth 3 javascript c# asp.net asp.net-mvc jquery

我的页面上有一些字段会出现并消失,具体取决于您在页面上的下拉选项.

所以,例如,我有

<section>
            @Html.LabelFor(model => model.AuctionTypeId)
            <div> @Html.DropDownList("AuctionTypeId", Model.AuctionTypes, @AuctionControllerResource.SelectAuctionType, new { id="auctionType", required = "required" })
                @Html.ValidationMessageFor(model => model.AuctionTypeId)       </div>
        </section>
        <section>
            @Html.LabelFor(model => model.AutomaticExtensionType, new { hidden = "true", id = "automaticExtensionTypeLabel" })
            <div> @Html.DropDownList("AutomaticExtensionType", Model.AutomaticExtensions, @AuctionControllerResource.SelectAutomaticExtensionType, new { hidden="hidden", required = "required", id = "automaticExtensionTypeList" }) 
                @Html.ValidationMessageFor(model => model.AutomaticExtensionType)       </div>
        </section>
Run Code Online (Sandbox Code Playgroud)

我对此的JQuery代码是

$('#auctionType').change(function () {
    var selectedAuctionType = $("#auctionType").val();
    var englishAuctionType = $("#englishAuctionTypeId").val();
    if (selectedAuctionType == englishAuctionType) {
        $("#automaticExtensionTypeList").show();
        $("#automaticExtensionTypeLabel").show();
    } else {
        $("#automaticExtensionTypeList").hide();
        $("#automaticExtensionTypeLabel").hide();
    }
});
Run Code Online (Sandbox Code Playgroud)

现在,他们应该展示和隐藏工作.问题是,当我提交表单并automaticExtensionTypeList隐藏字段时,表单不会提交,因为automaticExtensionTypeList它是必填字段.问题是如何告诉MVC仅验证可见字段?

我已经看了一下我们在这个项目中编写的一些JQuery,我们有这一行

$.validator.setDefaults({ ignore: [] });
Run Code Online (Sandbox Code Playgroud)

显然这可以实现隐藏验证.我的问题是,相反的代码行是什么?

Dav*_*ich 9

试试这个:

$.validator.setDefaults({
    ignore: ':hidden, [readonly=readonly]'
});
Run Code Online (Sandbox Code Playgroud)

或者用于定制

$.validator.setDefaults({
    ignore: "#automaticExtensionTypeList" 
});
Run Code Online (Sandbox Code Playgroud)


Ant*_*t P 5

这样做的原因是,隐藏字段不是设计时使用一个字段不适-他们设计用于在现场适用,但不要求用户输入.在您的情况下,您可以:

  • 除非适用,否则请使用视图逻辑来避免渲染字段.
  • 使用自定义验证器而不仅仅是平坦的验证器Required.
  • 在隐藏字段中使用有效的"默认"值.

就个人而言,我会选择最后一个,因为它实现起来最快,并且没有任何明显的缺陷 - 您可以在控制器中获取此默认值,然后根据需要进行操作.