使用ajax post调用如果ModelState为false的Jsonresult中返回ModelState的控制器。如何将ModelState正确绑定到DOM?
我将下面到目前为止的工作包括在内。
控制器:
if (ModelState.IsValid)
{
}
else
{
return new JsonResult(new { success = false, message = Utility.Errors(ModelState) });
}
JS:
$.ajax({
url: "@Url.Action("UpdateBio", "BioData")",
dataType: "json",
type: "POST",
data: formData,
success: function (response) {
if (response.success) {
toastr.success(response.message);
} else {
DisplayErrors(response.message);
toastr.error('Check form for validation errors!');
}
},
error: function () {
alert('An error occurred');
}
});
验证脚本:
function DisplayErrors(errors) {
for (var i = 0; i < errors.length; i++) {
var key = errors[i].Key;
var value = errors[i].Value[0];
$("[asp-validation-for='" + key + "']").remove();
$("<span asp-validation-for='" + key + "' class='text-danger'></span>").html(value).appendTo($("input#" + key).parent());
$("input#" + key).attr("class", 'form-control aper-validation-input');
}
}