0

View code :

$.post('@Url.Action("SetPlayers", "Game")', { name : t });

Controller code :

public class GameController : Controller
    {
            [HttpPost]
            public ActionResult SetPlayers(string name)
            {
                // some code...
                return RedirectToAction("Some Action");
            }
    }

When i set stop point on the method SetPlayers, method recieved variable and all worked but doesn't redirect to action. How can i change it?

user2204438
  • 61
  • 2
  • 7
  • `$.post` is the ajax request so you can not do this in controller side. Check [HERE](http://stackoverflow.com/questions/14667274/asp-net-mvc-partial-view-ajax-post) – AliRıza Adıyahşi Mar 25 '13 at 07:04

1 Answers1

1

$.post() sends an AJAX request to the server. The whole point of AJAX is to send an asynchronous HTTP request to your server without navigating away. If you want to redirect, don't use AJAX. You could use the window.location.href method instead:

window.location.href = '@Url.Action("SetPlayers", "Game")?name=' + encodeURIComponent(t);

Alternatively if you need to only conditionally redirect you could return JSON from your controller action pointing to the location you want to redirect and then perform the actual redirect on the client:

[HttpPost]
public ActionResult SetPlayers(string name)
{
    // some code...
    return Json(new redirectTo = { Url.Action("Some Action") });
}

and then:

$.post('@Url.Action("SetPlayers", "Game")', { name : t }, function(result) {
    if (result.redirectTo) {
        // the server returned The location to redirect to as JSON =>
        // let's redirect to this location
        window.location.href = result.redirectTo;
    }
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Typo? Shouldn't `rediretTo` be `redirectTo`? – Darin Dimitrov Mar 25 '13 at 07:46
  • Right answer : view code $.post('@Url.Action("SetPlayers", "Game")', { name: t }, function() { window.location.href = '@Url.Action("List", "Game")'; }); controller code [HttpPost] public void SetPlayers(string name) { // some code } Method SetPlayers doesn'n return value. – user2204438 Mar 25 '13 at 08:14