开发者

How to get all route-values after {controller}/{method}

I do render buttons in order to change the language as following:

                    <%: Html.ActionLink(
                        "EN", 
                        ViewContext.RouteData.Values["action"]开发者_开发技巧.ToString(), 
                        new { lang = "en" }, new { @class="tab" })%>

This would render me the link as follows: {...}\en\MyController\MyMethod - the only problem left is that I lose all routing values, which follow after the method's name. How is it possible to add them as well?

Thanks for any tips!


I actually use a few handy extension methods:

    public static RouteValueDictionary ToRouteValueDictionary(this NameValueCollection collection)
    {
        RouteValueDictionary dic = new RouteValueDictionary();
        foreach (string key in collection.Keys)
            dic.Add(key, collection[key]);

        return dic;
    }

    public static RouteValueDictionary AddOrUpdate(this RouteValueDictionary dictionary, string key, object value)
    {
        dictionary[key] = value;
        return dictionary;
    }

    public static RouteValueDictionary RemoveKeys(this RouteValueDictionary dictionary, params string[] keys)
    {
        foreach (string key in keys)
            dictionary.Remove(key);

        return dictionary;
    }

This allows me to do the following:

//Update the current routevalues and pass it as the values.
@Html.ActionLink("EN", ViewContext.RouteData.Values["action"], ViewContext.RouteData.Values.AddOrUpdate("lang", "en"))

//Grab the querystring, update a value, and set it as routevalues.
@Html.ActionLink("EN", ViewContext.RouteData.Values["action"], Request.QueryString.ToRouteValueDictionary.AddOrUpdate("lang", "en"))


I would suggest that you create a new HTML helper to do the job, as there is no neat way of doing what you want inside the view. It could look something like:

public static class MyHtmlHelpers {
  public static MvcHtmlString ChangeLanguageLink(this HtmlHelper html, string label, string newLang) {
    html.ViewContext.RouteData.Values["lang"] = newLang;
    return html.ActionLink(label, html.ViewContext.RouteData.Values["action"], ViewContext.RouteData.Values);
  }
}

And this is how you would use it in the view:

<%: Html.ChangeLanguageLink("EN", "en") %>


The simple way to get request parameters string is

var parameters = String.Join("&", Request.QueryString.AllKeys.Select(i => $"{i}={Request.QueryString[i]}"));

It can be used in controller and in the view as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜