RedirectToAction with parameter

C#asp.net MvcControllerRedirecttoaction

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

RedirectToAction with parameter:

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

Solution 4 - C#

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
          }

Solution 5 - C#

//How to use RedirectToAction in MVC

return RedirectToAction("actionName", "ControllerName", routevalue);

example

return RedirectToAction("Index", "Home", new { id = 2});

Solution 6 - C#

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.

Solution 7 - C#

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.

Solution 8 - C#

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.

Solution 9 - C#

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.

Solution 10 - C#

....

int parameter=Convert.ToInt32(Session["Id"].ToString());

....

return RedirectToAction("ActionName", new { Id = parameter });

Solution 11 - C#

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 });

Solution 12 - C#

If your need to redirect to an action outside the controller this will work.

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

Solution 13 - C#

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 } ) );

Solution 14 - C#

This one line of code will do it:

return Redirect("Action"+id);

Solution 15 - C#

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", "[email protected]");
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/[email protected]
}
[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
}

Solution 16 - C#

Also you can send any ViewBag, ViewData.. like this

return RedirectToAction("Action", new { Dynamic = ViewBag.Data= "any data" });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEric Brown - CalView Question on Stackoverflow
Solution 1 - C#Kurt SchindlerView Answer on Stackoverflow
Solution 2 - C#Eric Brown - CalView Answer on Stackoverflow
Solution 3 - C#kavitha ReddyView Answer on Stackoverflow
Solution 4 - C#CF5View Answer on Stackoverflow
Solution 5 - C#Thivan MydeenView Answer on Stackoverflow
Solution 6 - C#RohitView Answer on Stackoverflow
Solution 7 - C#mateuscbView Answer on Stackoverflow
Solution 8 - C#Zaeem QView Answer on Stackoverflow
Solution 9 - C#Toriq SagorView Answer on Stackoverflow
Solution 10 - C#aslanpayiView Answer on Stackoverflow
Solution 11 - C#Charles PhilipView Answer on Stackoverflow
Solution 12 - C#chr.solrView Answer on Stackoverflow
Solution 13 - C#BahamutView Answer on Stackoverflow
Solution 14 - C#AsIndeedView Answer on Stackoverflow
Solution 15 - C#mikemayView Answer on Stackoverflow
Solution 16 - C#SelcukBahView Answer on Stackoverflow