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?

John M
  • 14,338
  • 29
  • 91
  • 143
  • look [here](https://stackoverflow.com/questions/11370251/return-json-with-error-status-code-mvc/43069917), see if it helps – Bosco Jul 25 '19 at 22:08

1 Answers1

1

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);
    }
Jason Roner
  • 865
  • 1
  • 9
  • 14
  • I tried that but the method expects a Jsonresult to be returned. – John M Jul 25 '19 at 21:08
  • Change the return type of the method to ActionResult, and you can still use JsonResult along with returning a StatusCode() for your errors. – Jason Roner Jul 25 '19 at 21:18