我的页面上有一些字段会根据您在页面上所做的下拉选择出现和消失。
所以,例如,我有
<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>
我为此拥有的 JQuery 代码是
$('#auctionType').change(function () {
var selectedAuctionType = $("#auctionType").val();
var englishAuctionType = $("#englishAuctionTypeId").val();
if (selectedAuctionType == englishAuctionType) {
$("#automaticExtensionTypeList").show();
$("#automaticExtensionTypeLabel").show();
} else {
$("#automaticExtensionTypeList").hide();
$("#automaticExtensionTypeLabel").hide();
}
});
现在,显示和隐藏工作正常。问题是当我提交表单并且该字段automaticExtensionTypeList
被隐藏时,表单不会提交,因为automaticExtensionTypeList
它是必填字段。问题是如何告诉 MVC 只验证可见字段?
我浏览了我们在这个项目中编写的一些 JQuery,我们有这一行
$.validator.setDefaults({ ignore: [] });
显然,这可以实现隐藏验证。我的问题是,哪行代码相反?