RJP
RJP

Reputation: 4116

How to use RedirectToAction when posting to an action with ajax

I have the following jQuery:

 $.ajax({
                type: 'POST',
                url: "MyController/MyAction",
                data: $("form").serialize(),
                dataType: "json"
            });

And here is MyAction:

if(ModelState.IsValid)
{
   return RedirectToAction("OtherAction", new {id = 5});
}

I have this setup in three different places(three different actions). In two actions I can redirect just fine. However in one action I cannot redirect. Nothing happens, I just stay on the same page. I stepped through my code and all the lines are getting hit in MyAction, but my breakpoint in OtherAction never gets hit.

Is there something special I should be doing? In the two instances that work I am posting from/to the same controller. In the Instance above the jQuery is in a page under HomeController posting to an action in MyController

Upvotes: 0

Views: 105

Answers (1)

TGH
TGH

Reputation: 39248

This won't affect the main page since the redirect to action will just do a redirect and return the redirected response to the Ajax call.

The page that made the ajax request will not be redirected since the response is just seen as any other response. There was just one extra step (redirect) to arrive at the AJAX result.

If you want the main page to be redirected, you can handle that in the callback for the ajax request

Upvotes: 1

Related Questions