我有一个动作,我从一个锚调用,因此,站点/控制器/动作/ID,其中ID是一个int。

稍后,我需要从控制器重定向到相同的动作。

有什么聪明的办法吗?目前我在tempdata中存储ID,但当你 返回后,按f5再次刷新页面,tempdata消失,页面崩溃。


当前回答

我也有这个问题,如果你在同一个控制器中,一个很好的方法是使用命名参数:

return RedirectToAction(actionName: "Action", routeValues: new { id = 99 });

其他回答

//How to use RedirectToAction in MVC

return RedirectToAction("actionName", "ControllerName", routevalue);

例子

return RedirectToAction("Index", "Home", new { id = 2});
RedirectToAction("Action", "Controller" ,new { id });

为我工作,不需要做新的{id = id}

我重定向到同一个控制器内,所以我不需要“控制器”,但我不确定当控制器被要求作为参数时背后的具体逻辑。

如果有人想显示[httppost]的错误消息,那么他/她可以尝试通过传递一个ID使用

return RedirectToAction("LogIn", "Security", new { @errorId = 1 });

详情如下

 public ActionResult LogIn(int? errorId)
        {
            if (errorId > 0)
            {
                ViewBag.Error = "UserName Or Password Invalid !";
            }
            return View();
        }

[Httppost]
public ActionResult LogIn(FormCollection form)
        {
            string user= form["UserId"];
            string password = form["Password"];
            if (user == "admin" && password == "123")
            {
               return RedirectToAction("Index", "Admin");
            }
            else
            {
                return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
            }
}

希望它能正常工作。

这一行代码就可以做到:

return Redirect("Action"+id);

值得注意的是,您可以传递多个参数。id将用来构成URL的一部分,任何其他将通过参数后?在url中,并将UrlEncoded为默认值。

e.g.

return RedirectToAction("ACTION", "CONTROLLER", new {
           id = 99, otherParam = "Something", anotherParam = "OtherStuff" 
       });

所以url会是:

    /CONTROLLER/ACTION/99?otherParam=Something&anotherParam=OtherStuff

这些可以被你的控制器引用:

public ActionResult ACTION(string id, string otherParam, string anotherParam) {
   // Your code
          }