Problem
I have a Site/Controller/Action/ID action that I call from an anchor, where ID is an int.
Later on, I’ll need to route a Controller to the same Action.
Is there a creative way of accomplishing this? I’m currently storing ID in tempdata, but when you hit f5 to refresh the page after returning, the tempdata is no longer there, and the website crashes.
Asked by Eric Brown – Cal
Solution #1
The id can be passed to the RedirectToAction() method as part of the routeValues parameter.
return RedirectToAction("Action", new { id = 99 });
A redirect to Site/Controller/Action/99 will occur as a result of this. There’s no need for transient or any other type of view data.
Answered by Kurt Schindler
Solution #2
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, the first parameter (Action) appears to be disregarded when coded this way. It also doesn’t work if you merely specify the controller in the Dict and expect the first parameter to specify the Action.
If you arrive later, try Kurt’s solution first, and if that doesn’t work, try this one.
Answered by Eric Brown – Cal
Solution #3
RedirectToAction with parameter:
return RedirectToAction("Action","controller", new {@id=id});
Answered by kavitha Reddy
Solution #4
It’s also worth mentioning that you can pass multiple parameters through. id will be used to make up part of the URL and any others will be passed through as parameters after a ? in the url and will be UrlEncoded as default.
e.g.
return RedirectToAction("ACTION", "CONTROLLER", new {
id = 99, otherParam = "Something", anotherParam = "OtherStuff"
});
As a result, the url would be:
/CONTROLLER/ACTION/99?otherParam=Something&anotherParam=OtherStuff
These can then be referenced by your controller:
public ActionResult ACTION(string id, string otherParam, string anotherParam) {
// Your code
}
Answered by CF5
Solution #5
//How to use RedirectToAction in MVC
return RedirectToAction("actionName", "ControllerName", routevalue);
return RedirectToAction("Index", "Home", new { id = 2});
Answered by Thivan Mydeen
Post is based on https://stackoverflow.com/questions/1257482/redirecttoaction-with-parameter