【问题标题】:RedirectToAction with parameter带参数的 RedirectToAction
【发布时间】:2010-11-18 10:52:46
【问题描述】:

因此,我从锚点调用了一个动作,Site/Controller/Action/ID 其中IDint

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

有没有聪明的方法来做到这一点?目前我在 tempdata 中存储 ID,但是当你 返回后按f5再次刷新页面,临时数据消失,页面崩溃。

【问题讨论】:

  • 好问题...下面的答案中包含大量信息...实际上是站在巨人的肩膀上。

标签: c# asp.net-mvc controller redirecttoaction


【解决方案1】:

你也可以像这样发送任何 ViewBag、ViewData..

return RedirectToAction("Action", new { Dynamic = ViewBag.Data= "any data" });

【讨论】:

    【解决方案2】:

    这一行代码就能搞定:

    return Redirect("Action"+id);
    

    【讨论】:

      【解决方案3】:
      RedirectToAction("Action", "Controller" ,new { id });
      

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

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

      【讨论】:

      • RedirectToAction("Action", "Controller", new { id = id}); 正是我在 Core 3.1 应用中所需要的。
      • 我不知道为什么有时需要新的,但这里有两个很好:)
      【解决方案4】:

      使用 asp.net core 2.1 成功以下。它可能适用于其他地方。字典 ControllerBase.ControllerContext.RouteData.Values 可以从操作方法中直接访问和写入。也许这是其他解决方案中数据的最终目的地。它还显示了默认路由数据的来源。

      [Route("/to/{email?}")]
      public IActionResult ToAction(string email)
      {
          return View("To", email);
      }
      [Route("/from")]
      public IActionResult FromAction()
      {
          ControllerContext.RouteData.Values.Add("email", "mike@myemail.com");
          return RedirectToAction(nameof(ToAction));
               // will redirect to /to/mike@myemail.com
      }
      [Route("/FromAnother/{email?}")]`
      public IActionResult FromAnotherAction(string email)
      {
          return RedirectToAction(nameof(ToAction));
               // will redirect to /to/<whatever the email param says>
               // no need to specify the route part explicitly
      }
      

      【讨论】:

        【解决方案5】:

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

        例如

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

        所以网址是:

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

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

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

        【讨论】:

          【解决方案6】:

          如果有人想为[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 });
                      }
          }
          

          希望一切顺利。

          【讨论】:

            【解决方案7】:

            RedirectToAction 带参数:

            return RedirectToAction("Action","controller", new {@id=id});
            

            【讨论】:

            • 有效吗?我相信这是不正确的语法。如果我错了,请纠正我。
            • @pb2q new {id = id} 也能正常工作,因为框架知道您指的是哪个变量。
            【解决方案8】:
            //How to use RedirectToAction in MVC
            
            return RedirectToAction("actionName", "ControllerName", routevalue);
            

            示例

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

            【讨论】:

              【解决方案9】:

              如果您需要重定向到控制器外部的操作,这将起作用。

              return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
              

              【讨论】:

                【解决方案10】:

                如果您的参数恰好是一个复杂对象,this solves the problem。关键是RouteValueDictionary 构造函数。

                return RedirectToAction("Action", new RouteValueDictionary(Model))
                

                如果你碰巧有收藏,那就有点棘手了,but this other answer covers this very nicely

                【讨论】:

                  【解决方案11】:

                  Kurt's answer 应该是正确的,根据我的研究,但是当我尝试它时,我必须这样做才能让它真正为我工作:

                  return RedirectToAction( "Main", new RouteValueDictionary( 
                      new { controller = controllerName, action = "Main", Id = Id } ) );
                  

                  如果我没有在RouteValueDictionary 中指定控制器和操作,它将不起作用。

                  同样当这样编码时,第一个参数(Action)似乎被忽略了。所以如果你只是在Dict中指定控制器,并期望第一个参数指定Action,它也不起作用。

                  如果您稍后再来,请先尝试 Kurt 的回答,如果您仍有问题,请尝试此问题。

                  【讨论】:

                  • 很好的答案。另外,我相信controller 参数是可选的,如果重定向操作与您要重定向的操作位于同一控制器中。
                  • 应该是这样,但是当我这样做时,它不起作用,我不得不显式添加控制器......如果我有的话,这实际上是在我使用 MVC 的第一天现在猜猜我会说我有某种路由设置问题需要调查。
                  • 很奇怪。在 MVC4 中为我工作。
                  • 这发生在 MVC1 天,对其他人来说效果很好,这就是为什么我怀疑是配置问题,回头看。
                  • @EricBrown-Cal 考虑到您自己在 cmets 中提交的内容,您不认为 Kurt 的答案更适合那些寻求您刚开始时遇到的相同问题的答案的人吗?
                  【解决方案12】:

                  ....

                  int parameter = Convert.ToInt32(Session["Id"].ToString());
                  

                  ....

                  return RedirectToAction("ActionName", new { Id = parameter });
                  

                  【讨论】:

                    【解决方案13】:

                    MVC 4 示例...

                    请注意,您不必总是传递名为 ID 的参数

                    var message = model.UserName + " - thanks for taking yourtime to register on our glorious site. ";
                    return RedirectToAction("ThankYou", "Account", new { whatever = message });
                    

                    还有,

                    public ActionResult ThankYou(string whatever) {
                            ViewBag.message = whatever;
                            return View();
                    } 
                    

                    当然,如果您愿意,您可以将字符串分配给模型字段,而不是使用 ViewBag。

                    【讨论】:

                      【解决方案14】:

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

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

                      【讨论】:

                        【解决方案15】:

                        这可能是几年前的事了,但无论如何,这也取决于您的 Global.asax 地图路线,因为您可以添加或编辑参数以适应您的需求。

                        例如。

                        全球.asax

                            public static void RegisterRoutes(RouteCollection routes)
                            {
                                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                        
                                routes.MapRoute(
                                    "Default", // Route name
                                    "{controller}/{action}/{id}", // URL with parameters
                                    //new { controller = "Home", action = "Index", id = UrlParameter.Optional 
                                    new { controller = "Home", action = "Index", id = UrlParameter.Optional,
                                          extraParam = UrlParameter.Optional // extra parameter you might need
                                });
                            }
                        

                        那么您需要传递的参数将更改为:

                        return RedirectToAction( "Main", new RouteValueDictionary( 
                            new { controller = controllerName, action = "Main", Id = Id, extraParam = someVariable } ) );
                        

                        【讨论】:

                          【解决方案16】:

                          您可以将 id 作为 RedirectToAction() 方法的 routeValues 参数的一部分传递。

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

                          这将导致重定向到站点/控制器/操作/99。不需要临时或任何类型的视图数据。

                          【讨论】:

                          • 有没有这样做或类似的东西,但也指定控制器? (我需要从一个控制器到另一个控制器的操作)。
                          • @Diego:是的,有几个重载。在我的示例中,它将是 RedirectToAction("Action", "Controller", new{id=99}) msdn.microsoft.com/en-us/library/dd470154.aspx
                          • VB - Return RedirectToAction("Action", "Controller", New With {.id = 99})
                          • 有没有办法做同样的事情,但没有像这样的 url 更新?
                          • 值得注意的是,ID参数的名称对于参数在URL中的显示方式很重要,这取决于RouteConfig文件如何以及路由机制如何。例如,new { id = 100 } 可以生成 URL “/100”,而 new {groupId = 100} 可能被解释为查询字符串(如上所述),从而生成 URL “?groupId=100”。
                          猜你喜欢
                          • 2021-10-07
                          • 2014-09-16
                          • 1970-01-01
                          • 1970-01-01
                          • 2015-08-26
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          相关资源
                          最近更新 更多