我的ASP.NET MVC 5应用程序的剃刀视图使用两个复选框:
<div class="form-group">
@Html.LabelFor(model => model.BoolField1, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { @class = "form-control", @id = "bool1" } })
@Html.ValidationMessageFor(model => model.BoolField1, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.BoolField2, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.BoolField2, new { htmlAttributes = new { @class = "form-control", @id = "bool2" } })
@Html.ValidationMessageFor(model => model.BoolField2, "", new { @class = "text-danger" })
</div>
</div>
</div>
我试图实施BoolField2不能为真的规则,除非BoolField1也是如此。我的jquery代码:
function applyRule() {
var bool1Status = document.getElementById('bool1').checked;
var bool2Status = document.getElementById('bool2').checked;
if (bool2Status == true && bool1Status == false) {
// This is the sole error.
// Generate a suitable error message and display (how?)
}
}
此代码生成的自定义错误必须显示在Html.ValidationMessageFor中。我怎样才能做到这一点?
答案 0 :(得分:1)
首先,您需要更正EditorFor()的语法,它应该像
@Html.EditorFor(model => model.BoolField1, new { @class = "form-control", @id = "bool1" })
而不是
@Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { @class = "form-control", @id = "bool1" } })
现在,在进行此更正后,您可以编写自定义jQuery逻辑来实现相同的目标。这是代码。
$(function () {
$('#bool2').on('click', function (e) {
//Get the state of 1st checkbox
var isFirstCheck = $('#bool1').is(":checked");
if (isFirstCheck==false) {
//dispay message if you need. Below line of code will prevent user to select 2nd checkbox
e.preventDefault();
}
})
});