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

Display Custom Errors in Html.ValidationMessageFor via jQuery

本文关键字:显示 自定义 错误 ValidationMessageFor jQuery Html 通过      更新时间:2023-09-26

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

我试图实现这样一个规则,即除非BoolField1也是真的,否则BoolField2不可能是真的。我的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();
        }
    })
});