我在 asp.net MVC 应用程序上工作,我使用 ajax jQuery 调用 API 以防止单击提交按钮后更改 URL
来自
辞职/请求者索引?文件号=103085
到
辞职/请求者索引
并调用 ajax jQuery 工作成功,无需更改 URL,但同时验证注释模型状态不起作用。
那么如何显示验证?
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);
}
view 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 将调用 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 中删除
e.preventdefault
它将解决验证问题
但同时 URL 将从
更改Resignation/RequesterIndex?filenumber=103085 to Resignation/RequesterIndex
Ajax jQuery 工作成功,无需更改 URL,但在同一时间 验证注释模型状态不起作用。
那么如何显示验证?
好吧,首先@David所解释的是正确的,因为模型状态验证发生在服务器端,除非你使用razor,否则你的ajax或客户端不知道这一点。
另一点是,您将 jQuery 和 ModelState 客户端混合在一起,这不应该以这种方式工作。
当删除它时,验证工作正常,但同时 URL 会发生变化
那么如何使验证工作并且 URL 不改变?
不,您不需要更改或删除
e.preventdefault
。您可以做的是,设置一个 form id
并编写一个附加函数,并通过使用 $("#YourFormId").valid()
从 jQuery 中的验证属性中使用,以便保持所有现有代码不变,并且其简单且所需的更改较少。
让我们看看如何在实践中实现这一目标:
演示模型:
public class TestValidationModel
{
[Required(ErrorMessage = "Name field is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
}
控制器:
[HttpPost] 公共 IActionResult RequesterIndex(TestValidationModel 用户) { if (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>
}
输出: