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

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

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


当前回答

....

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

....

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

其他回答

RedirectToAction带参数:

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

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

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

这可能是几年前的事了,但无论如何,这也取决于你的全局。Asax映射路径,因为你可以添加或编辑参数,以适应你想要的。

eg.

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

下面的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
}

如果你需要重定向到控制器外的动作,这将工作。

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