将查询字符串作为路径值字典添加到ActionLink
我正在尝试创建一个ActionLink来从网格中导出数据。 网格由查询字符串中的值过滤。 这是url的一个例子:
http://www.mysite.com/GridPage?Column=Name&Direction=Ascending&searchName=text
这是将ActionLink添加到页面的代码:
@Html.ActionLink("Export to Excel", // link text "Export", // action name "GridPage", // controller name Request.QueryString.ToRouteDic(), // route values new { @class = "export"}) // html attributes
显示链接时,url为:
http://www.mysite.com/GridPage/Export?Count=3&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D
我究竟做错了什么?
试试这个:
我不确定这是最干净或最正确的方法,但确实有效
我没有使用你的扩展方法。 你必须重新整合:
@{ RouteValueDictionary tRVD = new RouteValueDictionary(ViewContext.RouteData.Values); foreach (string key in Request.QueryString.Keys ) { tRVD[key]=Request.QueryString[key].ToString(); } }
然后
@Html.ActionLink("Export to Excel", // link text "Export", // action name "GridPage", // controller name tRVD, new Dictionary { { "class", "export" } }) // html attributes
结果是
与class级出口
如果你看这里: http : //msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink.aspx
//You are currently using: ActionLink(HtmlHelper, String, String, String, Object, Object) //You want to be using: ActionLink(HtmlHelper, String, String, String, RouteValueDictionary, IDictionary)
交叉发布如何使用Html.BeginForm()将QueryString值转换为RouteValueDictionary?
这是一个帮助扩展,因此您可以在接受RouteValueDictionary
任何方法中转储查询字符串。
/// /// Turn the current request's querystring into the appropriate param for Html.BeginForm
or Html.ActionLink
/// /// /// /// /// See discussions: /// * https://stackoverflow.com/questions/4675616/how-do-i-get-the-querystring-values-into-a-the-routevaluedictionary-using-html-b /// * https://stackoverflow.com/questions/6165700/add-query-string-as-route-value-dictionary-to-actionlink /// public static RouteValueDictionary QueryStringAsRouteValueDictionary(this HtmlHelper html) { // shorthand var qs = html.ViewContext.RequestContext.HttpContext.Request.QueryString; // because LINQ is the (old) new black return qs.AllKeys.Aggregate(new RouteValueDictionary(html.ViewContext.RouteData.Values), (rvd, k) => { // can't separately add multiple values `?foo=1&foo=2` to dictionary, they'll be combined as `foo=1,2` //qs.GetValues(k).ForEach(v => rvd.Add(k, v)); rvd.Add(k, qs[k]); return rvd; }); }
您也可以从System.Collections.Specialized
尝试CopyTo
,如下所示:
var queryParams = new Dictionary(); Request.QueryString.CopyTo(queryParams); var routeValueDictionary = new RouteValueDictionary(queryParams);