使用 Ajax 调用和 JQuery 不显眼的 ModelState 验证
ModelState validation using Ajax call and JQuery unobstrusive
大家好,我正在尝试使用 Ajax/Jquery unobstrusive 验证输入。但是,在 ModelState 无效之后,我不知道如何处理 ajax 调用的 return 以及如何在 asp-validatation-for 标记上显示 'required text/regular expression'。有人可以帮忙吗?
在我的 .cshtml 上:
<label class="control-label">CodCard</label>
<input asp-for="CodCard" type="text" class="form-control small col-4" />
<span asp-validation-for="CodCard" class="text-danger"></span>
在我的 ViewModel 上:
[Required(ErrorMessage = "{0} must not be empty.")]
[Display(Name = "Code card")]
[StringLength(4, MinimumLength = 3, ErrorMessage = "Must be between {2} and {1} characters.")]
[RegularExpression("^[0-9]*$", ErrorMessage = "Must have only numbers.")]
public string CodCard { get; set; }
在我的 .js 上:
$(function () {
$("#btnChk").click('show.bs.modal', function () {
var options = {};
options.type = "POST";
options.url = "/api/CheckOut";
options.dataType = "JSON";
options.cache = false;
options.async = true;
contentType = "application/json; charset=utf-8",
options.data = {
"IdOrder": $("#IdOrder").val(),
"CodCard": $("#CodCard").val()
};
options.beforeSend = function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
};
options.success = function (data) {
if (!data.success) {
if (data.errors.length > 0) {
// I supposed to do something here, I am right?? But How?
//for (var i = 0; i < response.errors.length; i++) {
// var error = response.errors[i];
// alert(error);
//}
}
}
else
{
if (data.IdOrder!= null) {
window.location.href = "/app/order/order?Id=" + data.IdOrder;
}
// Error
if (data.errors == "fail") {
var modal = $("#itemLoader");
modal.find('.modal-body .spinner-border').hide();
modal.find('.modal-body .far').show();
}
}
};
options.error = function () {
$('.alertMsg').html("Error while making Ajax call!");
};
$.ajax(options);
});
});
我的控制器class:
[HttpPost("/api/CheckOut")]
public async Task<IActionResult> CheckOut([Bind("IdOrder, CodCard")] BagCheckOutViewModel checkOut)
{
...
if (!ModelState.IsValid)
{
return Json(new { success = false, errors = ModelState.Values.Where(i => i.Errors.Count > 0) });
}
...
这是一个关于如何在 ajax post 返回后显示模型状态错误的工作演示:
视图(Privacy.cshtml
):
@model BagCheckOutViewModel
<div id="myform">
<form>
<div>
<label class="control-label">CodCard</label>
<input asp-for="CodCard" type="text" class="form-control small col-4" />
<span asp-validation-for="CodCard" class="text-danger"></span>
</div>
<div>
<label class="control-label">IdOrder</label>
<input asp-for="IdOrder" type="text" class="form-control small col-4" />
<span asp-validation-for="IdOrder" class="text-danger"></span>
</div>
<div>
<input type="button" id="btnChk" value="click" />
</div>
</form>
</div>
脚本:
@section Scripts
{
<script type="text/javascript">
$(function () {
$("#btnChk").click('show.bs.modal', function () {
var options = {};
options.type = "POST";
options.url = "/api/CheckOut";
options.dataType = "JSON";
options.cache = false;
options.async = true;
contentType = "application/json; charset=utf-8",
options.data = {
"IdOrder": $("#IdOrder").val(),
"CodCard": $("#CodCard").val()
};
options.beforeSend = function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
};
options.success = function (data) {
//do your stuff...
};
options.error = function (res) {
$('#myform').html(res.responseText); //change here...
};
$.ajax(options);
});
});
</script>
}
控制器:
[HttpPost("/api/CheckOut")]
public async Task<IActionResult> CheckOut([Bind("IdOrder, CodCard")] BagCheckOutViewModel checkOut)
{
if (!ModelState.IsValid)
{
return PartialView("Privacy",checkOut);
}
return Json(new { success = true});
}
结果:
大家好,我正在尝试使用 Ajax/Jquery unobstrusive 验证输入。但是,在 ModelState 无效之后,我不知道如何处理 ajax 调用的 return 以及如何在 asp-validatation-for 标记上显示 'required text/regular expression'。有人可以帮忙吗?
在我的 .cshtml 上:
<label class="control-label">CodCard</label>
<input asp-for="CodCard" type="text" class="form-control small col-4" />
<span asp-validation-for="CodCard" class="text-danger"></span>
在我的 ViewModel 上:
[Required(ErrorMessage = "{0} must not be empty.")]
[Display(Name = "Code card")]
[StringLength(4, MinimumLength = 3, ErrorMessage = "Must be between {2} and {1} characters.")]
[RegularExpression("^[0-9]*$", ErrorMessage = "Must have only numbers.")]
public string CodCard { get; set; }
在我的 .js 上:
$(function () {
$("#btnChk").click('show.bs.modal', function () {
var options = {};
options.type = "POST";
options.url = "/api/CheckOut";
options.dataType = "JSON";
options.cache = false;
options.async = true;
contentType = "application/json; charset=utf-8",
options.data = {
"IdOrder": $("#IdOrder").val(),
"CodCard": $("#CodCard").val()
};
options.beforeSend = function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
};
options.success = function (data) {
if (!data.success) {
if (data.errors.length > 0) {
// I supposed to do something here, I am right?? But How?
//for (var i = 0; i < response.errors.length; i++) {
// var error = response.errors[i];
// alert(error);
//}
}
}
else
{
if (data.IdOrder!= null) {
window.location.href = "/app/order/order?Id=" + data.IdOrder;
}
// Error
if (data.errors == "fail") {
var modal = $("#itemLoader");
modal.find('.modal-body .spinner-border').hide();
modal.find('.modal-body .far').show();
}
}
};
options.error = function () {
$('.alertMsg').html("Error while making Ajax call!");
};
$.ajax(options);
});
});
我的控制器class:
[HttpPost("/api/CheckOut")]
public async Task<IActionResult> CheckOut([Bind("IdOrder, CodCard")] BagCheckOutViewModel checkOut)
{
...
if (!ModelState.IsValid)
{
return Json(new { success = false, errors = ModelState.Values.Where(i => i.Errors.Count > 0) });
}
...
这是一个关于如何在 ajax post 返回后显示模型状态错误的工作演示:
视图(Privacy.cshtml
):
@model BagCheckOutViewModel
<div id="myform">
<form>
<div>
<label class="control-label">CodCard</label>
<input asp-for="CodCard" type="text" class="form-control small col-4" />
<span asp-validation-for="CodCard" class="text-danger"></span>
</div>
<div>
<label class="control-label">IdOrder</label>
<input asp-for="IdOrder" type="text" class="form-control small col-4" />
<span asp-validation-for="IdOrder" class="text-danger"></span>
</div>
<div>
<input type="button" id="btnChk" value="click" />
</div>
</form>
</div>
脚本:
@section Scripts
{
<script type="text/javascript">
$(function () {
$("#btnChk").click('show.bs.modal', function () {
var options = {};
options.type = "POST";
options.url = "/api/CheckOut";
options.dataType = "JSON";
options.cache = false;
options.async = true;
contentType = "application/json; charset=utf-8",
options.data = {
"IdOrder": $("#IdOrder").val(),
"CodCard": $("#CodCard").val()
};
options.beforeSend = function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
};
options.success = function (data) {
//do your stuff...
};
options.error = function (res) {
$('#myform').html(res.responseText); //change here...
};
$.ajax(options);
});
});
</script>
}
控制器:
[HttpPost("/api/CheckOut")]
public async Task<IActionResult> CheckOut([Bind("IdOrder, CodCard")] BagCheckOutViewModel checkOut)
{
if (!ModelState.IsValid)
{
return PartialView("Privacy",checkOut);
}
return Json(new { success = true});
}
结果: