C# 如何使用 RedirectToAction 方法添加查询字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1067200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add querystring values with RedirectToAction method?
提问by mrblah
In asp.net mvc, I am using this code:
在 asp.net mvc 中,我使用以下代码:
RedirectToAction("myActionName");
I want to pass some values via the querystring, how do I do that?
我想通过查询字符串传递一些值,我该怎么做?
回答by Talljoe
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".
假设没有名为“value1”的路由参数。
回答by Martin_W
Also consider using T4MVC, which has the extension methods AddRouteValue()and AddRouteValues()(as seen on this question on setting query string in redirecttoaction).
还可以考虑使用T4MVC,它具有扩展方法AddRouteValue()和AddRouteValues()(如关于在 redirecttoaction 中设置查询字符串的这个问题所见)。
回答by Nick
Do not make the same mistake I was making. I was handling 404 errors and wanted to redirect with 404=filenamein the querystring, i.e. mysite.com?404=nonExistentFile.txt.
不要犯和我一样的错误。我正在处理 404 错误并希望404=filename在查询字符串中重定向,即mysite.com?404=nonExistentFile.txt.
QueryString Keys cannot begin with numbers. Changing from 404to FileNotFoundsolved my issue, i.e. mysite.com?FileNotFound=nonExistentFile.txt.
QueryString Keys 不能以数字开头。更改404为FileNotFound解决了我的问题,即mysite.com?FileNotFound=nonExistentFile.txt.
回答by Pieter-Jan Van Robays
For people like me who were looking to add the CURRENT querystring values to the RedirectToAction, this is the solution:
对于像我这样希望将 CURRENT 查询字符串值添加到 RedirectToAction 的人来说,这是解决方案:
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 RouteValueDictionaryobject
如您所见,解决方案是使用RouteValueDictionary对象

