45

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.

xaisoft
  • 3,343
  • 8
  • 44
  • 72

1 Answers1

83

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;
    }
});
mouldycurryness
  • 69
  • 1
  • 11
Tommy
  • 39,592
  • 10
  • 90
  • 121
  • Hi, Is this mainly for security, so you can't redirect a users browser to some page that might have a malicious script? – xaisoft Nov 15 '13 at 22:11
  • @xaisoft i think it's more of a lack of functionality than a security decision. – Kevin B Nov 15 '13 at 22:12
  • 1
    @xaisoft No, it a HTTP limitation. During a normal PRG (Post, Redirect, Get), the server receives a form POST, processes it and returns a HTTP 301/302 redirect to another page which the browser receives and follows. JS/AJAX do not know how to handle a 301/302 redirect as it is expecting a HTTP 200 response with a payload (Json, HTML, text) attached with it. – Tommy Nov 15 '13 at 22:12
  • 1
    If you wanted it to redirect, you should post using a basic form anyway. – Kevin B Nov 15 '13 at 22:12
  • @Tommy - I have an ajax post that calls one action method and if that is succesful, it makes another ajax post which is supposed to redirect. How can I make the second call non-ajax? – xaisoft Nov 16 '13 at 19:01
  • @xaisoft - are you submitting a form on your second call? – Tommy Nov 16 '13 at 22:49
  • @Tommy - The second call checks if a session is valid and is supposed to redirect the user to the homepage. – xaisoft Nov 16 '13 at 23:45
  • you can also use window.location.href = '@Url.Action("actionName","controllername")'; – Amol Shiledar Dec 23 '14 at 14:09
  • what if you want to change all model properties – Sana Ahmed Jan 28 '19 at 13:20