jqueryasp.net-mvcasp.net-mvc-3exceptionhandleerror

How to redirect to another view from catch block using MVC


I'm calling a function from AJAX

$.ajax({
         type: "POST",
         url: "GetOneApple",
         data: {},
         dataType: "json",
         success: function (data) {}
});

Home Controller :

[HttpPost]
public ActionResult GetOneApple()
{
     try
       {
      ..snip
       }
     catch (Exception e)
       {
           return RedirectToAction("ErrorPage", "Home");
       }
}

In catch block I have also tried this:

return new RedirectToRouteResult(new RouteValueDictionary {
    { "Controller", "Home" }, 
    { "Action", "ErrorPage" }
});

I have a ErrorPage controller like this

 public ActionResult ErrorPage()
        {
            return View();
        }

as i mentioned,
if any error occurred in the try block it has to redirect to ErrorPage but page is not redirecting, using firebug i got the "ErrorPage" html in the AjaxResponse from the controller, even though its not redirecting to "ErrorPage" view

What am i missing? I´m kind of new to this, so hopefully there is a simple answer that i haven´t been able to find...


Solution

  • You are mixing up two concepts:

    1. REST interface being consumed by an AJAX call
    2. Web application that you would like to navigate to an error page.

    Your REST API should always respond to the request, never ask the client to redirect. Instead, in case of an error, return the error details in JSON format, e.g.

    { status: "error", message: "Error so and so" }
    

    along with an error HTTP code. You can achieve this like so:

    catch (Exception ex)
    {
        Response.StatusCode = 500; // put a reasonable code here
        return Json(new { status = "error", message = ex.Message });
    }
    

    In your JavaScript, you can AJAX can use the error callback to "catch" that. Your JavaScript then decides what to do next. If you want to display the error to the user, you can use JavaScript to render the message as HTML.

    (Remark: You would usually redirect your browser to an error page only if the whole page request is invalid. If you are on a valid page and only one AJAX call is failing you wouldn't want to unload the valid page and go to an error page URL(?). Even if your browser makes a page request that fails, I generally prefer to render an error response from that very URL rather than redirecting the browser to a "error page". The reason is that a redirect changes the address in the address bar and adds itself to the history. For example, if your user wants to retry by clicking the "refresh" button, the browser will not redo the same thing that was leading to an error before. Instead it will simply reload the error page, even if the original use case might now work.)