2011-05-29 107 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; 
     }); 
}