提问人:ahmed abdelaziz 提问时间:9/12/2023 最后编辑:ahmed abdelaziz 更新时间:9/13/2023 访问量:79
当使用 ajax jQuery 验证注解调用 api 不起作用时?
when call api using ajax jQuery validation annotation not working?
问:
我在 ASP.NET Core MVC应用程序上工作,我使用ajax jQuery调用API,以防止在单击提交按钮后更改URL。
从
Resignation/RequesterIndex?filenumber=103085
自
Resignation/RequesterIndex
并在不更改 URL 的情况下调用 ajax jQuery 工作成功,但同时验证注解模型状态不起作用。
如何显示验证?
public class ResignationRequester
{
[Required]
[Display(Name = "Dept./ Branch: ")]
public string Dept { get; set; }
[Required]
[Display(Name = "Designation: ")]
public string Designation { get; set; }
}
控制器动作方法:
public class ResignationController : Controller
{
public ActionResult RequesterIndex(string filenumber)
{
return View(resignationRequester);
}
[HttpPost]
public ActionResult RequesterIndex(ResignationRequester resignationRequester)
{
if (ModelState.IsValid)
{
try
{
Workforce.InsertToReignation(resignationRequester, (string)Session[SessionKeys.Username], (DateTime)Session[SessionKeys.LastWorkingDate], noticeperiod, (int)Session[SessionKeys.UserCode]);
}
catch (Exception ex)
{
ViewBag.errorMsg = "Create Not Done Correctly";
}
Session[SessionKeys.DirectManager] = GetEmployeeName(Convert.ToString(resignationRequester.DirectManager));
Session[SessionKeys.LineManager] = GetEmployeeName(Convert.ToString(resignationRequester.LineManager));
if (string.IsNullOrEmpty(ViewBag.errorMsg))
{
ViewBag.successMessage = "Resignation Submission form Created successfully";
}
}
else
{
var errors = ModelState.Select(x => x.Value.Errors)
.Where(y => y.Count > 0)
.ToList();
ViewBag.errorMsg = "Some Required Fields Not Added";
goto InvalidModel;
}
}
else
{
ViewBag.errorMsg = "No Data For This File No";
}
InvalidModel:
ViewBag.isPostBack = true;
return View(resignationRequester);
}
}
视图ResignationRequester.cshtml
@model HR.WorkforceRequisition.Models.ResignationRequester
@{
ViewBag.Title = "Requester Index";
}
@using (Html.BeginForm("RequesterIndex", "Resignation", FormMethod.Post, new { enctype = "multipart/form-data", @id = "ResignationApp", style = "padding-top: 50px" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@if (!string.IsNullOrEmpty(ViewBag.errorMsg))
{
<div class="alert alert-danger">
@ViewBag.errorMsg
</div>
}
@if (!string.IsNullOrEmpty(ViewBag.successMessage))
{
<div class="alert alert-success">
@ViewBag.successMessage
</div>
}
<div class="row">
<div class="form-group col-md-6 hover">
<div class="col-md-5">
@Html.LabelFor(model => model.Dept, htmlAttributes: new { @class = "control-label" })
</div>
<div class="col-md-7">
@Html.EditorFor(model => model.Dept, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Dept, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group col-md-6 hover">
<div class="col-md-5">
@Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "control-label" })
</div>
<div class="col-md-7">
@Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-12">
<input type="submit" value="Submit" class="btn btn-success" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
调用 jQuery ajax 将调用操作 Requester Index on Resignation Controller
$("#ResignationApp").submit(function (e) {
e.preventDefault(); // Prevent the default form submission
var formData = $(this).serialize();
console.log("data is" + formData)
$.ajax({
type: "POST",
url: '@Url.Action("RequesterIndex", "Resignation")',
data: formData,
success: function (response) {
$("#successMessage").show();
},
error: function (error) {
console.error(error);
}
});
});
我对此进行了调查,并在ajax jQuery调用中发现了问题
e.preventDefault();
删除它时,验证工作,但同时 URL 会更改
如何使验证工作并且 URL 不更改?
预期结果
当将部门或职务留空时,它必须显示我需要的验证
未更改 URL 时所需的验证错误
但这并没有发生......
如果我从jQuery中删除,它将解决问题验证,但同时URL将从:e.preventdefault
Resignation/RequesterIndex?filenumber=103085
自
Resignation/RequesterIndex
更新的帖子
if ($("#validateFrom").valid()) {
运行 valid() 需要哪些 jQuery 脚本 或者你的意思是 validate()
答:
Ajax jQuery 在不更改 URL 的情况下成功运行,但同时 验证注解模型状态不起作用。
那么如何显示验证呢?
好吧,首先@David所解释的是正确的,因为模型状态验证是在服务器端进行的,除非您使用 razor,否则您的 ajax 或客户端不知道这一点。
另一点是,您将客户端(即 jQuery 和 ModelState)混合在一起,这不应该以这种方式工作。
删除它时,验证有效,但同时 URL 将更改
那么如何使验证工作并且 URL 不更改?
不,您不需要更改或删除 .您可以做的是,设置一个 and 并编写一个附加函数,并使用 from jQuery 中的验证属性,以便保持所有现有代码的原样,并且其简单且需要的更改更少。e.preventdefault
form id
$("#YourFormId").valid()
让我们在实践中看看我们如何实现这一目标:
演示模型:
public class TestValidationModel
{
[Required(ErrorMessage = "Name field is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
}
控制器:
[HttpPost的] public IActionResult RequesterIndex(TestValidationModel 用户) { 如果 (ModelState.IsValid) {
}
return View();
}
视图:
@model MVCWebApp.Controllers.TestValidationModel
<form id="validateFrom">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" id="txtName" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-secondary" id="btnSubmit">Submit</button>
</div>
</form>
@section Scripts
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<script>
$(function () {
$('#btnSubmit').click(function () {
if ($("#validateFrom").valid()) {
$('#validateFrom').submit();
}
else {
return false;
}
});
$("#validateFrom").on("submit", function (event) {
event.preventDefault();
var formData = $(this).serialize();
console.log("data is" + formData)
$.ajax({
type: "POST",
url: '@Url.Action("RequesterIndex", "ModelStateValidation")',
data: formData,
success: function (response) {
$("#successMessage").show();
}
});
});
})
</script>
}
注意:如您所见,通过使用它将检查表单值,并根据正确的输入,它将继续提交表单。$("#validateFrom").valid()
输出:
评论
"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"
评论