0

コードを表示:

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

コントローラーコード:

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

メソッドSetPlayersにストップポイントを設定すると、メソッドは変数を受け取り、すべてが機能しましたが、アクションにリダイレクトされません。どうすれば変更できますか?

4

1 に答える 1

1

$.post()AJAXリクエストをサーバーに送信します。AJAXの要点は、ナビゲートせずに非同期HTTPリクエストをサーバーに送信することです。リダイレクトする場合は、AJAXを使用しないでください。window.location.href代わりに次の方法を使用できます。

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

または、条件付きでリダイレクトするだけでよい場合は、リダイレクトする場所を指すコントローラーアクションからJSONを返し、クライアントで実際のリダイレクトを実行できます。

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

その後:

$.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;
    }
});
于 2013-03-25T07:11:47.567 に答える