首页 文章

带参数的RedirectToAction

提问于
浏览
486

我有一个我从锚中调用的动作, Site/Controller/Action/ID 其中 IDint .

稍后我需要从Controller重定向到同一个Action .

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

14 回答

  • 165

    RedirectToAction 带参数:

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

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

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

    这可能是几年前,但无论如何,这也取决于您的Global.asax Map 路线,因为您可以添加或编辑参数以适合您的需要 .

    例如 .

    Global.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 } ) );
    
  • 37

    ....

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

    ....

    return RedirectToAction("ActionName", new { Id = parameter });
    
  • 49
    RedirectToAction("Action", "Controller" ,new { id });
    

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

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

  • 38

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

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

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

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

    如果你以后再来,先试试Kurt的答案,如果你还有问题,试试这个 .

  • 37

    值得注意的是,您可以传递多个参数 . id将用于构成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
              }
    
  • 7

    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(如果这是您的首选项) .

  • 15

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

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

    如果你碰巧有收藏品,它会让它变得有点棘手,but this other answer covers this very nicely .

  • 0

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

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

    这将导致重定向到Site / Controller / Action / 99 . 不需要临时或任何类型的视图数据 .

  • 5

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

    [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
    }
    
  • 14

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

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

    如果想要显示 [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 });
                }
    }
    

    希望它工作正常 .

  • 1
    //How to use RedirectToAction in MVC
    
    return RedirectToAction("actionName", "ControllerName", routevalue);
    

    例子

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

相关问题