如何将QueryString放回ActionLink?

时间:2018-02-01 09:35:18

标签: c# asp.net-mvc .net-4.0

我的操作链接是根据以下代码生成的:

@{
    var routeValues = this.ViewContext.RouteData.Values;
    var queryString = this.Request.QueryString;
    var controller = routeValues["controller"] as string;
    var action = routeValues["action"] as string;
}
<ul class="list-inline">
    <li>@Resources.Global.Language : </li>
    <li>
        @Html.ActionLink("English", @action, @controller, new { culture = "en" }, new { rel = "alternate", hreflang = "en" })
    </li>
    <li>
        @Html.ActionLink("中文", @action, @controller, new { culture = "zh" }, new { rel = "alternate", hreflang = "zh" })
    </li>
</ul>

如何将queryString放回ActionLink? 我的queryString将使用一个或多个参数动态

2 个答案:

答案 0 :(得分:2)

您不应该将您的查询字符串视为字符串。它已被解析并放入Request.QueryString。您只需将该字典传递给ActionLink即可。唯一的额外步骤是为每个链接添加不同的密钥并确保使用correct overload of ActionLink

@functions
{
    RouteValueDictionary MergeIn(IDictionary<string, object> original_data, object more_data)
    {
        var result = new RouteValueDictionary(original_data);
        foreach (var k in HtmlHelper.ObjectToDictionary(more_data)) 
        {
            result[k.Key] = k.Value;
        }
        return result;
    }
}

@{
    var query_values = new Dictionary<string, object>();
    this.Request.QueryString.CopyTo(query_values);
}
<ul class="list-inline">
    <li>
        @Html.ActionLink("English", null, MergeIn(query_values, new { culture = "en" }), HtmlHelper.ObjectToDictionary(new { rel = "alternate", hreflang = "en" }))
    </li>
    <li>
        @Html.ActionLink("中文", null, MergeIn(query_values, new { culture = "zh" }), HtmlHelper.ObjectToDictionary( new { rel = "alternate", hreflang = "zh" }))
    </li>
</ul>

答案 1 :(得分:-1)

我在stackoverflow上的另一个问题中找到了一个解决方案: https://stackoverflow.com/a/26533136/2424987

在这个解决方案中,drzaus从查询字符串创建一个新的RouteValueDictionary。 然后,您可以将所需的新参数放入字典中,并将其传递给actionlink方法。

这是drzaus建议的代码:

/// <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;
    });
}