I have an action I call from an anchor thusly, Site/Controller/Action/ID
where ID
is an int
.
Later on I need to redirect to th
//How to use RedirectToAction in MVC
return RedirectToAction("actionName", "ControllerName", routevalue);
return RedirectToAction("Index", "Home", new { id = 2});
RedirectToAction("Action", "Controller" ,new { id });
Worked for me, didn't need to do new{id = id}
I was redirecting to within the same controller so I didn't need the "Controller"
but I'm not sure on the specific logic behind when the controller is required as a parameter.
Kurt's answer should be right, from my research, but when I tried it I had to do this to get it to actually work for me:
return RedirectToAction( "Main", new RouteValueDictionary(
new { controller = controllerName, action = "Main", Id = Id } ) );
If I didn't specify the controller and the action in the RouteValueDictionary
it didn't work.
Also when coded like this, the first parameter (Action) seems to be ignored. So if you just specify the controller in the Dict, and expect the first parameter to specify the Action, it does not work either.
If you are coming along later, try Kurt's answer first, and if you still have issues try this one.
If your parameter happens to be a complex object, this solves the problem. The key is the RouteValueDictionary
constructor.
return RedirectToAction("Action", new RouteValueDictionary(Model))
If you happen to have collections, it makes it a bit trickier, but this other answer covers this very nicely.
This might be years ago but anyways, this also depends on your Global.asax map route since you may add or edit parameters to fit what you want.
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
});
}
then the parameters you'll need to pass will change to:
return RedirectToAction( "Main", new RouteValueDictionary(
new { controller = controllerName, action = "Main", Id = Id, extraParam = someVariable } ) );
You can pass the id as part of the routeValues parameter of the RedirectToAction() method.
return RedirectToAction("Action", new { id = 99 });
This will cause a redirect to Site/Controller/Action/99. No need for temp or any kind of view data.