I work on asp.net MVC application I call API using ajax jQuery to prevent change URL after click submit button
from
Resignation/RequesterIndex?filenumber=103085
to
Resignation/RequesterIndex
and call ajax jQuery working success without change URL but on same time validation annotation model state not working .
so How to display validation ?
public class ResignationRequester
{
[Required]
[Display(Name = "Dept./ Branch: ")]
public string Dept { get; set; }
[Required]
[Display(Name = "Designation: ")]
public string Designation { get; set; }
}
controller action
public class ResignationController : Controller
{
public ActionResult RequesterIndex(string filenumber)
{
return View(resignationRequester);
}
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()
@if (!string.IsNullOrEmpty(ViewBag.errorMsg))
{
@ViewBag.errorMsg
}
@if (!string.IsNullOrEmpty(ViewBag.successMessage))
{
@ViewBag.successMessage
}
@Html.LabelFor(model => model.Dept, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Dept, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Dept, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
call jQuery ajax will call action 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);
}
});
});
I do investigation about that and found issue on ajax jQuery call
e.preventDefault();
when remove it validation working but on same time URL will change
so How to make validation working and URL not changed ?
Expected result
when leave department or designation empty then it must display validation required for me
required validation error without change URL
but this not happen
if i remove e.preventdefault from jQuery it will solve issue validation
but on same time URL will change from
Resignation/RequesterIndex?filenumber=103085 to Resignation/RequesterIndex
Mohammad HussainPosted Sep 12, 2023, 8:01 AM
The issue you're encountering is because you're preventing the default form submission by using
e.preventDefault()in your jQuery Ajax submission code. When you prevent the default form submission, client-side validation (jQuery Validation) doesn't get triggered because the form is not submitted to the server, and hence, validation doesn't work as expected.To maintain validation and prevent the URL from changing, you can use the following approach:
Remove
e.preventDefault()from your jQuery Ajax submission code.Modify your form to use a regular button instead of a submit button:
Add an event listener to the button click event to perform the Ajax submission and prevent the form from being submitted: