Skip to main content
 首页 » 编程设计

c#之RedirectToAction 不适用于 $.post

2024年02月06日13Renyi-Fan

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

[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"); 
    } 

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

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

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

请您参考如下方法:

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

在行动中而不是:

return RedirectToAction("Logout", "Home"); 

做:

return Content(Url.Action("Logout", "Home")); 

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

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

或在 Action 结束时调用 call javascript:

var script = "window.loaction ='"+Url.Action("Logout","Home")+"' ;"; 
return JavaScript(script);