gpt4 book ai didi

javascript - 通过 jQuery 在 Html.ValidationMessageFor 中显示自定义错误

转载 作者:行者123 更新时间:2023-12-03 08:00:58 25 4
gpt4 key购买 nike

我的 ASP.NET MVC 5 应用程序的 Razor View 使用两个复选框:

<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>

我正在尝试实现以下规则:除非 BoolField1 也为 true,否则 BoolField2 不能为 true。我的 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 中。我怎样才能实现这个目标?

最佳答案

首先您需要更正 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();
}
})
});

关于javascript - 通过 jQuery 在 Html.ValidationMessageFor 中显示自定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34575730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com