-1

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

  1. 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.

  2. 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)
    });
    
  3. 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:

  1. What’s the most maintainable way to map ModelState errors to form fields?

  2. Should I reformat API errors or handle the default ModelState structure?

  3. Are there libraries/plugins that simplify this workflow?

Environment:

  • ASP.NET MVC 5
  • jQuery 3.6
  • Bootstrap 4
New contributor
Oyemahak is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.