ChatGPT解决这个技术问题 Extra ChatGPT

RedirectToAction with parameter

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.

Great question...there is a wealth of info in the answers below...were literally standing on the shoulders of giants.

K
Kurt Schindler

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.


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: yes, there's are a couple overloads for that. In my example it would be RedirectToAction("Action", "Controller", new{id=99}) msdn.microsoft.com/en-us/library/dd470154.aspx
VB - Return RedirectToAction("Action", "Controller", New With {.id = 99})
Is there a way to do the same thing but not have the url update like so?
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".
C
Community

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.


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.
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.
Weird. Works for me in MVC4.
This happened back in MVC1 days, and it worked fine for others, that's why I suspect a configuration issue, looking back.
@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?
p
pb2q

RedirectToAction with parameter:

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

Does it work? I believe this is incorrect syntax. Correct me if I'm wrong.
@pb2q new {id = id} works just as well because the framework knows which variable you are referring to.
C
CF5

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
          }

T
Thivan Mydeen
//How to use RedirectToAction in MVC

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

example

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

R
Rohit

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.


C
Community

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.


Z
Zaeem Q
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.
I don't know why the new is sometimes needed, but it's good to have both here :)
T
Toriq Sagor

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.


a
aslanpayi
....

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

....

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

C
Charles Philip

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

c
chr.solr

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

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

B
Bahamut

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

A
AsIndeed

This one line of code will do it:

return Redirect("Action"+id);

m
mikemay

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
}

C
CinCout

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

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

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now