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 this same Action from a Controller.
Is there a clever way to do this? Currently I'm stashing ID
in tempdata, but when you hit f5 to refresh the page again after going back, the tempdata is gone and the page crashes.
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.
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.
controller
parameter is optional if the redirect action is in the same controller as the action you're redirecting from.
RedirectToAction
with parameter:
return RedirectToAction("Action","controller", new {@id=id});
new {id = id}
works just as well because the framework knows which variable you are referring to.
It is also worth noting that you can pass through more than 1 parameter. 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"
});
So 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
}
//How to use RedirectToAction in MVC
return RedirectToAction("actionName", "ControllerName", routevalue);
example
return RedirectToAction("Index", "Home", new { id = 2});
MVC 4 example...
Note that you do not always have to pass parameter named 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();
}
Of course you can assign string to model fields instead of using ViewBag if that is your preference.
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.
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.
RedirectToAction("Action", "Controller", new { id = id});
was just what I needed in my Core 3.1 app.
If one want to Show error message for [httppost]
then he/she can try by passing an ID using
return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
for Details like this
public ActionResult LogIn(int? errorId)
{
if (errorId > 0)
{
ViewBag.Error = "UserName Or Password Invalid !";
}
return View();
}
[Httppost]
public ActionResult LogIn(FormCollection form)
{
string user= form["UserId"];
string password = form["Password"];
if (user == "admin" && password == "123")
{
return RedirectToAction("Index", "Admin");
}
else
{
return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
}
}
Hope it works fine.
....
int parameter=Convert.ToInt32(Session["Id"].ToString());
....
return RedirectToAction("ActionName", new { Id = parameter });
I had this issue as well, and quite a nice way to do it if you are within the same controller is to use named parameters:
return RedirectToAction(actionName: "Action", routeValues: new { id = 99 });
If your need to redirect to an action outside the controller this will work.
return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
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 } ) );
This one line of code will do it:
return Redirect("Action"+id);
The following succeeded with asp.net core 2.1. It may apply elsewhere. The dictionary ControllerBase.ControllerContext.RouteData.Values is directly accessible and writable from within the action method. Perhaps this is the ultimate destination of the data in the other solutions. It also shows where the default routing data comes from.
[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
}
Also you can send any ViewBag, ViewData.. like this
return RedirectToAction("Action", new { Dynamic = ViewBag.Data= "any data" });
Success story sharing
Return RedirectToAction("Action", "Controller", New With {.id = 99})