簡體   English   中英

在data-ajax-success調用中以編程方式在ValidationSummary中添加錯誤

[英]Add an error in ValidationSummary programmatically in data-ajax-success call

我成功地展示了一個包含jQuery unobstrusive驗證器檢測到的錯誤的ValidationSummary

<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);
};

我能做什么 ?

當您使用mvc的客戶端驗證時, jquery.validate.unobtrusive.js插件解析文檔並在jquery.validate.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();刪除它們vs.find('.myerror').remove();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM