RedirectToAction not working after successful jquery ajax post?

xaisoft picture xaisoft · Nov 15, 2013 · Viewed 47.4k times · Source

The following does not redirect my page: Here is the MVC code:

    [HttpPost]
    public ActionResult GoHome()
    { 
         return RedirectToAction("Index", "Home");   
    }

Here is the ajax post:

   $.support.cors = true;

            $.ajax({
                type: "POST",
                url: "http://localhost/UserAccount/GoHome",
                dataType: 'json',
                crossDomain: true
            });

The post is successful and when it hists the GoHome action it does not redirect to the Index Action of the Home Controller.

Answer

Tommy picture Tommy · Nov 15, 2013

You cannot redirect from an AJAX post. You could return the URL you want to redirect the browser to however and redirect from Javascript.

Controller

[HttpPost]
public ActionResult GoHome()
{ 
     return Json(Url.Action("Index", "Home"));   
}

Javascript

$.ajax({
    type: "POST",
    url: "http://localhost/UserAccount/GoHome",
    dataType: 'json',
    crossDomain: true,
    success: function (data) {
        window.location.href = data;
    }
});