Friday, March 17, 2017

Example of How to Return Errors to JavaScript ajax() Calls from a MVC .Net Controller

Recently I needed to return error codes to an ajax() call in JavaScript from a .Net MVC Controller  using an ActionResult.

Here's one way to do it:

In the Controller:



[HttpGet]
public ActionResult MyControllerMethod()
{
 ...
   bool happyPath = ....
   bool error1 = ...
   if (happyPath)
      {
         return PartialView("_Makes", viewModel);
      }
    else
      {
      if(error1)
      {
         Response.StatusCode = (int) HttpStatusCode.BadRequest;
         Response.StatusDescription = "CustomError1"; //variable "errorThown" in ajax recieving call
         return Content("CustomError1");
      } else {
         Response.StatusCode = (int) HttpStatusCode.InternalServerError;
         Response.StatusDescription = "CustomError1"; //variable "errorThown" in ajax recieving call
         return Content("CustomError2");
      }
}

 Then call this Controller in your JavaScript and display appropriate error JavaScript messages

function getMyControllerMethodStuff() {
    var myUrl = '../Home/MyControllerMethod';
    $.ajax({url: myUrl, type: "GET", datatype: 'html'})
        .fail(function (jqXhr, textStatus, errorThrown) {
            if (errorThrown === "CustomError1") {
                displayCustomErrorAlert1();
            } else {
                displayCustomErrorAlert2();
            }
        })
        .done(function (data) {
    // happy path
    ...
        });
}

No comments: