在data-ajax-success调用中以编程方式在ValidationSummary中添加错误

时间:2018-03-27 09:34:54

标签: javascript c# jquery ajax asp.net-core-mvc

我成功地显示ValidationSummary,其中包含jQuery不显眼的验证器检测到的错误:

<form asp-controller="PlanningYearsEditModal" asp-action="EditPlanningYear" data-ajax="true" data-ajax-method="POST" data-ajax-success="onSuccess">
    <div id="content" class="modal-body">
        @Html.ValidationSummary(false, null, new { @class = "text-danger" })
        <table class="inner" style="width:100%" border=1>
            <tr class="azurbox rounded3 white bold">
                <td style="width:20%">@CommonResources.CommonField</td>
                <td style="width:80%">@CommonResources.CommonValue</td>
            </tr>
            <tr class="underline">
                <td>@Html.LabelFor(model => model.LabelFr)</td>
                <td>
                    @Html.EditorFor(model => model.LabelFr)
                    @Html.ValidationMessageFor(model => model.LabelFr, "*", new { @class = "text-danger" })
                </td>
            </tr>
            <tr class="underline">
                <td>@Html.LabelFor(model => model.LabelNl)</td>
                <td>
                    @Html.EditorFor(model => model.LabelNl)
                    @Html.ValidationMessageFor(model => model.LabelNl, "*", new { @class = "text-danger" })
                </td>
            </tr>
        </table>
    </div>
    <div class="modal-footer">
        @Html.HiddenFor(model => model.Id)
        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="submit" class="btn">Save changes</button>
        <div id="Results"></div>
    </div>
</form>

经过这些简单的检查后,我必须在我的控制器中进行手动完整性检查,控制器返回包含错误的JSON。我想使用验证器能够在ValidationSummary中显示这些错误。我可以手动用jQuery更新html代码,但它会导致很多问题(有时候验证摘要已经存在,有时候不会,有时你只需要更换几个子弹,有时候不会......)

我觉得有可能以一种干净的方式做到这一点。

我试过这样的东西,但它没有在屏幕上显示任何东西(我可以确认是在调用代码):

var onSuccess = function (errors) {
    var errorArray = {};
    errorArray["LabelFr"] = 'Some error thrown by the controller';
    $('#myForm').validate().showErrors(errorArray);
};

我该怎么办?

1 个答案:

答案 0 :(得分:3)

当您使用mvc的客户端验证时,jquery.validate.unobtrusive.js插件会解析文档并在$.validator中配置jquery.validate.js。您不应尝试修改$.validator或致电validate()

您的@Html.ValidationSummary()生成<div>[data-valmsg-summary]属性),其中包含<ul>元素。要添加消息,只需添加包含错误消息的<li>元素

即可
var vs = $('[data-valmsg-summary]'); // get the div
if (errorArray.length > 0) {
    // update class name
    vs.addClass('validation-summary-errors').removeClass('validation-summary-valid');
}
$.each(errorArray, function(index, item) {
    // add each error
    vs.children('ul').append($('<li></li>').text(item));
});

如果多次调用此方法,并且您不想显示以前添加的错误,则可以为<li>元素指定一个类名称,例如

vs.children('ul').append($('<li class="myerror"></li>').text(item));

然后使用vs.find('.myerror').remove();

删除它们