0

My ajax call:

  $.ajax({
     url: './Orders/SaveOrder',
     type: "POST",
     data: JSON.stringify(data),
     dataType: "JSON",
     contentType: "application/json",
     success: function (d) {
     if (d.status == true) {
          alert('Successfully saved.');
       }
       else {
             alert('Failed' + d.ErrorMessage);
        }
       },
       error: function (error) {
         alert('Error. Please try again.');
        }

And my SaveOrder controller action:

  [HttpPost]
  public JsonResult SaveOrder(OrderVM o)
  {
    try
            {
                if (ModelState.IsValid)
                {
                      // do some database work
                    }
                }

                return new JsonResult { Data = new { status = status} };
            }
            catch (Exception ex)
            {
                // how to return jsonresult with error?
            }
        }

How do I get the ajax request to receive the details from the try-catch catch block? Specifically how does the 'error: function...' section get the code back?

1
  • look here, see if it helps Commented Jul 25, 2019 at 22:08

1 Answer 1

2

you can try:

return new HttpStatusCodeResult(500, ex.Message);

I believe this would work with Ajax and you can get the error message from the error parameter. Hope it works!

edit: For the ajax error, you can access the error message:

    error: function (error) {
        alert(error.statusText);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that but the method expects a Jsonresult to be returned.
Change the return type of the method to ActionResult, and you can still use JsonResult along with returning a StatusCode() for your errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.