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 });
}