【问题标题】:When i want redirect to action with method post(javascript), controller method does not redirect and return to previous page, why?当我想使用 post(javascript) 方法重定向到操作时,控制器方法不会重定向并返回上一页,为什么?
【发布时间】:2013-03-25 07:01:49
【问题描述】:

查看代码:

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

控制器代码:

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

当我在方法 SetPlayers 上设置停止点时,方法接收到变量并且所有工作都有效,但没有重定向到操作。怎么改?

【问题讨论】:

  • $.post 是 ajax 请求,因此您不能在控制器端执行此操作。检查HERE

标签: javascript asp.net-mvc


【解决方案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;
    }
});

【讨论】:

  • 错字? rediretTo 不应该是 redirectTo 吗?
  • 正确答案:查看代码 $.post('@Url.Action("SetPlayers", "Game")', { name: t }, function() { window.location.href = ' @Url.Action("列表", "游戏")'; });控制器代码 [HttpPost] public void SetPlayers(string name) { // 一些代码 } 方法 SetPlayers 没有返回值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 2021-11-21
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多