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

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

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


当前回答

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

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

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

其他回答

这可能是几年前的事了,但无论如何,这也取决于你的全局。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 } ) );

值得注意的是,您可以传递多个参数。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
          }

如果您的参数恰好是一个复杂的对象,这就解决了问题。关键是RouteValueDictionary构造函数。

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

如果你碰巧有集合,这就有点棘手了,但另一个答案很好地涵盖了这个问题。

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

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

这一行代码就可以做到:

return Redirect("Action"+id);