712

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.

Keerthi
  • 525
  • 8
  • 14
Eric Brown - Cal
  • 14,135
  • 12
  • 58
  • 97

16 Answers16

1159

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 Schindler
  • 21,037
  • 4
  • 43
  • 48
  • 2
    Is there anyway of doing that or something similar but also specifying the controller? (I need to do that from one controller to an action of other controller). – Diego May 26 '11 at 12:44
  • 21
    @Diego: yes, there's are a couple overloads for that. In my example it would be RedirectToAction("Action", "Controller", new{id=99}) http://msdn.microsoft.com/en-us/library/dd470154.aspx – Kurt Schindler May 27 '11 at 13:32
  • 10
    VB - `Return RedirectToAction("Action", "Controller", New With {.id = 99})` – Jeremy A. West Mar 26 '14 at 16:10
  • Is there a way to do the same thing but not have the url update like so? – Worthy7 Jun 22 '16 at 06:42
  • @KurtSchindler Anyway to update your answer to include your comment example of a redirect to different controller as well? To help those who might skip over reading comments. – Edward Mar 25 '17 at 17:04
  • I have a similar need and am doing this. Works, but it places the data in the query string in the browser URL. For me it's a user id and I can't have that info appear there. Any way to do it under the covers? Think maybe I'll post this separately. – Robert Dec 20 '17 at 17:44
  • For information about passing objects as json strings, see https://stackoverflow.com/questions/7597863/passing-object-in-redirecttoaction – wpqs Aug 12 '18 at 10:51
  • 4
    It's worth noting that the name of the ID parameter matters in terms of how the parameter appears in the URL, which is based on how the RouteConfig file is and how routing mechanisms are. For instance, new { id = 100 } can produce the URL "/100", while new {groupId = 100} might be interpreted as a query string (as was mentioned above), resulting in the URL "?groupId=100". – jakobinn Jan 27 '19 at 12:57
212

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.

Community
  • 1
  • 1
Eric Brown - Cal
  • 14,135
  • 12
  • 58
  • 97
  • 7
    Great answer. Also, I believe the `controller` parameter is optional if the redirect action is in the same controller as the action you're redirecting from. – mellis481 Oct 28 '14 at 14:51
  • 1
    it's supposed to be, but when I did it that way, it didn't work, I had to explicitly add the controller... that was literally in my first days of MVC, if I had to guess now I'd say I had some kind of routing setup issue to look into. – Eric Brown - Cal Oct 28 '14 at 16:16
  • Weird. Works for me in MVC4. – mellis481 Oct 28 '14 at 17:03
  • This happened back in MVC1 days, and it worked fine for others, that's why I suspect a configuration issue, looking back. – Eric Brown - Cal Oct 28 '14 at 19:39
  • 1
    @EricBrown-Cal Given even your own submission in your comments don't you think Kurt's answer is better suited for those seeking an answer to the same issue you had in your beginning days? – Edward Mar 25 '17 at 17:06
  • Except for the fact it didn't work for me to solve the problem in question, yes. Given that, explaining both those facts seemed the most useful answer. SO doesn't allow dual answers, so I upvoted Kirk's and marked the one that actually solved my issue. – Eric Brown - Cal Mar 27 '17 at 14:10
  • I am doing this and it works. But the data appears in the query string in the browser URL. My parameter is a user ID so I can't have it display there. Any way to do this under the covers? Maybe I'll post this separately. – Robert Dec 20 '17 at 17:48
  • This works for me also the option from pb2q works. I suppose depends how you have set the routhing in your project one or another option may not work. This solved my issue – user2693802 Sep 13 '20 at 22:57
  • Given it's age, i moved the answer to Kurt's answer. – Eric Brown - Cal Feb 19 '21 at 20:44
75

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(int id, string otherParam, string anotherParam) {
   // Your code
          }
CF5
  • 1,123
  • 9
  • 19
74

RedirectToAction with parameter:

return RedirectToAction("Action","controller", new {@id=id});
pb2q
  • 58,613
  • 19
  • 146
  • 147
kavitha Reddy
  • 3,303
  • 24
  • 14
47
//How to use RedirectToAction in MVC

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

example

return RedirectToAction("Index", "Home", new { id = 2});
Thivan Mydeen
  • 1,461
  • 11
  • 7
43

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.

Rohit
  • 3,059
  • 1
  • 14
  • 4
31

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.

Community
  • 1
  • 1
mateuscb
  • 10,150
  • 3
  • 52
  • 76
30
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.

Zaeem Q
  • 485
  • 5
  • 11
23
....

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

....

return RedirectToAction("ActionName", new { Id = parameter });
aslanpayi
  • 805
  • 7
  • 10
20

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.

Toriq Sagor
  • 199
  • 1
  • 3
17

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 });
Charles Philip
  • 267
  • 1
  • 4
  • 8
10

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

return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
chr.solr
  • 576
  • 1
  • 7
  • 19
8

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 } ) );
Bahamut
  • 1,929
  • 8
  • 29
  • 51
3

This one line of code will do it:

return Redirect("Action"+id);
AsIndeed
  • 138
  • 1
  • 13
2

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
}
mikemay
  • 3,707
  • 6
  • 34
  • 35
1

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

return RedirectToAction("Action", new { Dynamic = ViewBag.Data= "any data" });
CinCout
  • 9,486
  • 12
  • 49
  • 67
SelcukBah
  • 49
  • 5