how to add querystring values with RedirectToAction method?

C#asp.net MvcUrl Redirection

C# Problem Overview


In asp.net mvc, I am using this code:

RedirectToAction("myActionName");

I want to pass some values via the querystring, how do I do that?

C# Solutions


Solution 1 - C#

Any values that are passed that aren't part of the route will be used as querystring parameters:

return this.RedirectToAction
  ("myActionName", new { value1 = "queryStringValue1" });

Would return:

/controller/myActionName?value1=queryStringValue1

Assuming there's no route parameter named "value1".

Solution 2 - C#

For people like me who were looking to add the CURRENT querystring values to the RedirectToAction, this is the solution:

var routeValuesDictionary = new RouteValueDictionary();
Request.QueryString.AllKeys.ForEach(key => routeValuesDictionary.Add(key, Request.QueryString[key]));
routeValuesDictionary.Add("AnotherFixedParm", "true");
RedirectToAction("ActionName", "Controller", routeValuesDictionary);

The solution as you can see is to use the RouteValueDictionary object

Solution 3 - C#

Also consider using T4MVC, which has the extension methods AddRouteValue() and AddRouteValues() (as seen on this question on setting query string in redirecttoaction).

Solution 4 - C#

Do not make the same mistake I was making. I was handling 404 errors and wanted to redirect with 404=filename in the querystring, i.e. mysite.com?404=nonExistentFile.txt.

QueryString Keys cannot begin with numbers. Changing from 404 to FileNotFound solved my issue, i.e. mysite.com?FileNotFound=nonExistentFile.txt.

Solution 5 - C#

If you already have a query string from somewhere, you can skip parsing and reassembling the query string and just use Redirect with Url.Action:

string queryString ="?param1=xxx&page=5";
return Redirect(Url.Action("MyAction") + queryString);

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
QuestionmrblahView Question on Stackoverflow
Solution 1 - C#TalljoeView Answer on Stackoverflow
Solution 2 - C#Pieter-Jan Van RobaysView Answer on Stackoverflow
Solution 3 - C#Martin_WView Answer on Stackoverflow
Solution 4 - C#NickView Answer on Stackoverflow
Solution 5 - C#Alex from JitbitView Answer on Stackoverflow