I’m implementing AJAX-based teacher updates in an ASP.NET MVC 5 application with server-side validation. While my API correctly returns validation errors (e.g., 400 Bad Request with ModelState
), I can’t reliably display these errors in the browser.
What I Tried
Manual Error Parsing:
error: function(xhr) { const errors = xhr.responseJSON?.ModelState; if (errors) { for (const [key, value] of Object.entries(errors)) { $(`#${key}`).after(`<div class="error">${value}</div>`); } } }
Problem: The nested ModelState structure (e.g., {"teacher.HireDate":["Invalid date"]}) makes field mapping messy.
Simplified API Response - modified the API to return a flattened format:
return BadRequest(new { Errors = ModelState.Values.SelectMany(v => v.Errors) .Select(e => e.ErrorMessage) });
jQuery validation plugin:
$("#teacherForm").validate({ submitHandler: function(form) { // AJAX submit } });
Problem: doesn't integrate with server-side validation responses
What I expected
A clean way to:
- Extract field-specific errors from
ModelState
- Dynamically display them under corresponding form inputs
- Maintain consistency with Bootstrap’s validation styles
Current code - API controller:
[HttpPut]
[Route("api/teachers/{id}")]
public IHttpActionResult UpdateTeacher(int id, [FromBody] Teacher teacher)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Returns error object
}
// ... update logic
}
AJAX call:
$.ajax({
url: `/api/teachers/${teacherId}`,
type: 'PUT',
contentType: 'application/json',
data: JSON.stringify(teacherData),
success: function() { /* ... */ },
error: function(xhr) {
// NEED HELP: Cleanly display errors here
}
});
Questions:
What’s the most maintainable way to map
ModelState
errors to form fields?Should I reformat API errors or handle the default
ModelState
structure?Are there libraries/plugins that simplify this workflow?
Environment:
- ASP.NET MVC 5
- jQuery 3.6
- Bootstrap 4