RedirectToAction 不适用于 $.post

Sat*_*pto 1 c# asp.net-mvc jquery razor

我有个问题。我正在尝试使用控制器方法重定向我的应用程序,如下所示:

[HttpPost]
    public ActionResult GetSelected(string Selected, string NewRoleID)
    {
        var StringSelected = Selected.Split(',');
        for (var i = 0; i < StringSelected.Count(); i++)
        {
            if (StringSelected[i] == "true")
            {
                R_ROLEMENU newMenu = new R_ROLEMENU();
                newMenu.RoleID = int.Parse(NewRoleID);
                newMenu.MenuID = i + 1;
                var existing = (from item in db.RoleMenus
                                where (item.RoleID == newMenu.RoleID && item.MenuID == newMenu.MenuID)
                                select item).ToArray();
                if (existing.Count() == 0)
                {
                    db.RoleMenus.Add(newMenu);
                    db.SaveChanges();
                }
            }
            else
            {
                R_ROLEMENU oldMenu = new R_ROLEMENU();
                oldMenu.RoleID = int.Parse(NewRoleID);
                oldMenu.MenuID = i + 1;
                var existing = (from item in db.RoleMenus
                                where (item.RoleID == oldMenu.RoleID && item.MenuID == oldMenu.MenuID)
                                select item).ToArray();
                if (existing.Count() != 0)
                {
                    db.RoleMenus.Remove(existing[0]);
                    db.SaveChanges();
                }
            }
        }
        return RedirectToAction("Logout", "Home");
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用 jquery 调用该方法,如下所示:

$.post("/m_menu/getselected?selected=" + selectedmenus + "&newroleid=" + roleid, function () {
                    //todo
        });
Run Code Online (Sandbox Code Playgroud)

问题是,应用程序一直重定向到索引页面,而不是主控制器中的注销操作。我究竟做错了什么?控制器中的其余代码运行良好,只是重定向不起作用。请帮忙,谢谢

Ehs*_*jad 5

因为它是一个 ajax 调用RedirectToAction将简单地返回称为视图的动作作为帖子的响应,您必须通过$.post回调函数中的jquery 重定向:

在行动中而不是:

return RedirectToAction("Logout", "Home");
Run Code Online (Sandbox Code Playgroud)

做:

return Content(Url.Action("Logout", "Home"));
Run Code Online (Sandbox Code Playgroud)

并在$.post 的回调中执行以下操作:

$.post("/m_menu/getselected?selected=" + selectedmenus + "&newroleid=" + roleid, function (response) {
                  window.location =  response;
        });
Run Code Online (Sandbox Code Playgroud)

或在动作结束时调用 call javascript:

var script = "window.loaction ='"+Url.Action("Logout","Home")+"' ;";
return JavaScript(script);
Run Code Online (Sandbox Code Playgroud)