我有一个动作,我从一个锚调用,因此,站点/控制器/动作/ID,其中ID是一个int。
稍后,我需要从控制器重定向到相同的动作。
有什么聪明的办法吗?目前我在tempdata中存储ID,但当你 返回后,按f5再次刷新页面,tempdata消失,页面崩溃。
我有一个动作,我从一个锚调用,因此,站点/控制器/动作/ID,其中ID是一个int。
稍后,我需要从控制器重定向到相同的动作。
有什么聪明的办法吗?目前我在tempdata中存储ID,但当你 返回后,按f5再次刷新页面,tempdata消失,页面崩溃。
当前回答
RedirectToAction("Action", "Controller" ,new { id });
为我工作,不需要做新的{id = id}
我重定向到同一个控制器内,所以我不需要“控制器”,但我不确定当控制器被要求作为参数时背后的具体逻辑。
其他回答
....
int parameter=Convert.ToInt32(Session["Id"].ToString());
....
return RedirectToAction("ActionName", new { Id = parameter });
Kurt的答案应该是正确的,从我的研究来看,但当我尝试它时,我必须这样做才能让它真正为我工作:
return RedirectToAction( "Main", new RouteValueDictionary(
new { controller = controllerName, action = "Main", Id = Id } ) );
如果我没有在RouteValueDictionary中指定控制器和动作,它就不能工作。
同样,当像这样编码时,第一个参数(Action)似乎被忽略了。因此,如果您只是在Dict中指定控制器,并期望第一个参数指定Action,那么它也不起作用。
如果你稍后再来,先试试Kurt的答案,如果你还有问题,试试这个。
这可能是几年前的事了,但无论如何,这也取决于你的全局。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 } ) );
MVC 4的例子…
注意,您并不总是必须传递名为ID的参数
var message = model.UserName + " - thanks for taking yourtime to register on our glorious site. ";
return RedirectToAction("ThankYou", "Account", new { whatever = message });
And,
public ActionResult ThankYou(string whatever) {
ViewBag.message = whatever;
return View();
}
当然,你可以将字符串分配给模型字段,而不是使用ViewBag,如果这是你的偏好。
//How to use RedirectToAction in MVC
return RedirectToAction("actionName", "ControllerName", routevalue);
例子
return RedirectToAction("Index", "Home", new { id = 2});