Issue with saving single record the form saves multiple records until the modelstate is valid

Asif_360 20 Reputation points
2025-01-27T07:05:16.65+00:00

I am using asp.net core 8
i have a popup form when i click submit with empty fields it returns required validation error and when i fill data in fields then submit again it save multiple records is sql database the number of time i click on submit before all the fields are valid

 function initializeFormScripts() {
     $('#addEmployeeForm').submit(function (e) {
         e.preventDefault();
         const form = $(this);
         $.ajax({
             url: form.attr('action'),
             type: form.attr('method'),
             data: form.serialize(),
             success: function (response) {
                 if (response.success) {
                     closePopup();
                     showSuccessMessage();
                   } else {
                     // Update the partial view content with validation errors
                     $('#addEmployeeFormContainer').html(response.html);
                     initializeFormScripts();  
                 }
             },
             error: function () {
                 alert('An error occurred while saving the data.');
             }
         });
     });
}

Model

 public class AddEmployeeViewModel   : IValidatableObject
 {
     public AddEmployeeViewModel()
     {
         EmployeeTypeId = 0;   
         NumberOfDept = 0;    
         HasSubDept = false;
     }
     [Required(ErrorMessage = "نوع الثلاجة مطلوب")]
     public int EmployeeTypeId { get; set; } = 0;
     [Required(ErrorMessage = "Error")]
     [Range(1, int.MaxValue, ErrorMessage = " Error 0")]
     public int NumberOfDept { get; set; } = 1; // Set default value
     public bool HasSubDept { get; set; } = false; // Set default value
     public List<int> SelectedDepartments{ get; set; } = new(); 
       public int MaxNumberOfDept{ get; set; } = 5;  
   
     public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
     {
         if (NumberOfDept <= 0 || NumberOfDept > MaxNumberOfDept)
         {
             yield return new ValidationResult(
                 $" Error message {MaxNumberOfDept}",
                 new[] { nameof(NumberOfDept ) }
             );
         }
          if (HasSubDept && (SelectedDepartments== null || !SelectedDepartments.Any()))
         {
             yield return new ValidationResult(
                 " Error message",
                 new[] { nameof(SelectedDepartments) }
             );
         }
     }
 }

@model Mortuary.Models.AddEmployeeViewModel
<form asp-action="AddEmployeePartial" asp-controller="Employee" method="post" id="addEmployeeForm">
    @Html.AntiForgeryToken()

		-----inputs here   

 <div class="form-groupleft">
        <button type="button" class="btn btn-primarySearch" onclick="closePopup()">Close</button>
        <button type="submit" class="btn btn-primary" style="width:100px">Save</button>
       
    </div>
 
</form> 
[HttpPost]
[ValidateAntiForgeryToken]
 public async Task<IActionResult> AddEmployeePartial(AddEmployeeViewModel model, ICollection<Drawer> Departments)
 {
     if (!ModelState.IsValid)
     {
         return PartialView("_AddEmployeePartial", model);
     }
     if (ModelState.IsValid){  _context.Employee.Add(refrigerator);
  await _context.SaveChangesAsync();
  return Json(new { success = true });
     }var errors = ModelState
.Where(ms => ms.Value.Errors.Any())
.ToDictionary(
    kvp => kvp.Key,
    kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
);
return Json(new { success = false,errors });
}
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
774 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,757 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,244 questions
{count} votes

Accepted answer
  1. AgaveJoe 29,676 Reputation points
    2025-01-27T16:20:30.0533333+00:00

    The number of times the submission fails due to !ModelState.IsValid corresponds to the number of records saved."

    In my opinion, the general design has a lot of problems but I believe the reported issue is due to calling initializeFormScripts() multiple times. Each call to initializeFormScripts() adds a submit handler the #addEmployeeForm from.

    Place a break point in the AddEmployeePartial method. I'm guessing the action is called twice. The browser's Network tool (dev tools) also shows the AJAX requests being made.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.