IKI*_*KN2 4 javascript c# ajax jquery 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>
Run Code Online (Sandbox Code Playgroud)
在这些简单的检查之后,我必须在我的控制器中进行手动完整性检查,控制器返回JSON包含错误的一个。我想使用验证器来在 ValidationSummary 中显示这些错误。我可能会更新 html 代码jQuery手动,但它会导致很多问题(有时验证摘要已经存在,有时不存在,有时您只需要替换几个项目符号,有时不,......)。
我觉得可能有一种方法可以以干净的方式做到这一点。
我试过这样的事情,但它没有在屏幕上显示任何内容(我可以确认正在调用代码):
var onSuccess = function (errors) {
var errorArray = {};
errorArray["LabelFr"] = 'Some error thrown by the controller';
$('#myForm').validate().showErrors(errorArray);
};
Run Code Online (Sandbox Code Playgroud)
我能做什么 ?
小智 6
当您使用 mvc 的客户端验证时,jquery.validate.unobtrusive.js插件会解析文档并配置$.validatorin 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));
});
Run Code Online (Sandbox Code Playgroud)
如果这被多次调用,并且您不想显示以前添加的错误,则可以为<li>元素指定一个类名,例如
vs.children('ul').append($('<li class="myerror"></li>').text(item));
Run Code Online (Sandbox Code Playgroud)
然后使用删除它们 vs.find('.myerror').remove();
| 归档时间: |
|
| 查看次数: |
2428 次 |
| 最近记录: |