我的页面上有一些字段会出现并消失,具体取决于您在页面上的下拉选项。
所以,例如,我有
<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: [] });
显然这可以实现隐藏验证。我的问题是,相反的代码行是什么?
答案 0 :(得分:9)
试试这个:
$.validator.setDefaults({
ignore: ':hidden, [readonly=readonly]'
});
或用于自定义
$.validator.setDefaults({
ignore: "#automaticExtensionTypeList"
});
答案 1 :(得分:5)
原因是隐藏字段不适用于字段不适用时 - 它们设计用于字段 应用但不需要输入用户。在您的情况下,您可以:
Required
。就个人而言,我会选择最后一步,因为它实现起来最快,并且没有任何明显的缺陷 - 您可以在控制器中获取此默认值,然后根据需要进行操作。
答案 2 :(得分:4)
这是一个常见问题。
希登斯不会停止验证。
我总是通过创建具有重叠属性的多个表单来处理这个问题。
示例:强>
<div id="HasControlls">
@Using(Html.BeginForm)
{
@Html.LabelFor(model => model.AuctionTypeId)
@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>
}
<div id="HasNotControlls">
@Using(Html.BeginForm)
{
@Html.LabelFor(model => model.AuctionTypeId)
@Html.DropDownList("AuctionTypeId", Model.AuctionTypes, @AuctionControllerResource.SelectAuctionType, new { id="auctionType", required = "required" })
@Html.ValidationMessageFor(model => model.AuctionTypeId) </div>
</section>
<section>
@Html.ValidationMessageFor(model => model.AutomaticExtensionType) </div>
</section>
}