2011-05-29 110 views
10

我试图创建一个ActionLink从网格导出数据。网格由查询字符串中的值过滤。下面是URL的一个例子:添加查询字符串作为路由值字典到ActionLink

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 

当显示的链接,网址是:

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 

我究竟做错了什么?

+0

您尝试不工作的原因是.ToString()在Dictionary 类中没有重载(并且它不应该是,因为它用于存储更多不仅仅是路由字典参数)。 – 2011-05-29 03:40:37

回答

24

试试这个:

我不知道这是最干净的或最正确的方式,但它确实工作

我没有使用你的扩展方法。你必须重返认为:

@{ 
    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<string, object> { { "class", "export" } }) // html attributes 

结果

Results

与类出口enter image description here

+1

我认为这会将查询字符串转换为a = 1&a = 2变成a = 1,2 – zod 2013-05-02 16:07:53

+0

QueryString.GetValues绕过这个问题(它返回一个字符串数组),但我还不知道如何将它添加到RouteValueDictionary – zod 2013-05-02 16:13:59

+0

Hey @zod,你有没有发现如何将它们添加到RouteValueDictionary中?我找不到方法。 – mcNux 2014-07-29 13:35:24

1

How do I get the QueryString values into a the RouteValueDictionary using Html.BeginForm()?

跨张贴在这里只是一个辅助扩展,使您可以在接受RouteValueDictionary任何方法转储查询字符串。

/// <summary> 
/// Turn the current request's querystring into the appropriate param for <code>Html.BeginForm</code> or <code>Html.ActionLink</code> 
/// </summary> 
/// <param name="html"></param> 
/// <returns></returns> 
/// <remarks> 
/// 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 
/// </remarks> 
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; 
     }); 
}