s

HTML Attributes

return an error to the front-end from an API when ModelState.IsValid equals false edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 10 December 2023 | 0

To return an error to the front-end from an API when ModelState.IsValid equals false, you need to handle this within your API endpoint method. Assuming you're using ASP.NET Core, here's an example of how you can do this:

Solution

This is how I am returning the error to html front end from web api action method

                if (ModelState.IsValid)
                {
                    var retval = await new Received().Update(id, received);
                    return Json(new { success = true });
                }
                else
                {
                    var errorMessage = string.Empty;
                    foreach (var state in ModelState.Values)
                    {
                        foreach (var error in state.Errors)
                        {
                            errorMessage = errorMessage   "
" error.ErrorMessage; // Handle or log the error message } } // Model validation failed, return the model with errors to the view return BadRequest(errorMessage);

and in the front end you can use this code
Here's the html code

                <div id="errorEditDetailsModal" class="row alert alert-danger">
                    <strong>Error!</strong>  <span id="editDetailsModalErrorMessage"></span>
                </div>

Here's the javascript code

                error: function (error) {
                    $("#errorEditDetailsModal").show();
                    $("#editDetailsModalErrorMessage").html(error.responseText);
                    console.log("Error updating data: ", error);)
                    Cursor.hide();
                }