更新: 我要问的是是否可以仅在客户端删除从 View 模型中字段的属性推断出的验证规则。
--
当从下拉列表中做出选择时,我将切换某些字段的显示。我还需要切换验证。
ViewModel.cs:
public int ddlTypeID { get; set; }
public Dictionary<int, string> ddlTypes { get; set; }
[Required(ErrorMessageResourceName = "msgRequired",
ErrorMessageResourceType = typeof(Resources.Globals))]
public DateTime firstDate {get; set;}
[Required(ErrorMessageResourceName = "msgRequired",
ErrorMessageResourceType = typeof(Resources.Globals))]
public DateTime otherDate {get; set;}
创建.cshtml:
<script type="text/javascript">
$(document).ready(function () {
$('.optional').hide();
$('#ddlTypeID').change(function () {
var id = $(this).val();
if (id == 1) {
$('.optional').show();
} else {
$('.optional').hide();
}
});
});
</script>
@using (Html.BeginForm())
{
<div class="editor-field">
@Html.DropDownListFor(x=>x.ddlTypeID, new SelectList(Model.ddlTypes,"Key","Value",Model.ddlTypeID),Resources.Globals.msgType)
@Html.ValidationMessageFor(model => model.ddlTypeID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.firstDate )
</div>
<div class="editor-field">
@Html.EditorFor(model => model.firstDate )
@Html.ValidationMessageFor(model => model.firstDate )
</div>
<div class="editor-label optional">
@Html.LabelFor(model => model.otherDate )
</div>
<div class="editor-field optional">
@Html.EditorFor(model => model.otherDate )
@Html.ValidationMessageFor(model => model.otherDate )
</div>
<input type="submit" value="Save" />
}
这可以隐藏/显示 otherDate 的字段 - 但如何同时切换验证?或者有更好的方法吗?
请您参考如下方法:
它确实有效。 但是当表单上有隐藏元素时,您需要调用此代码。 正确的代码是:
function IgnoreValidationForHiddenElements() {
$.validator = $("#formid").validate(
{
ignore: ":hidden"
});
}
或者当你穿上
$(document).ready(function () {
//Your Code
}
当您在加载表单时需要此选项时。
