Search code examples
c#asp.net-mvc-2asp.net-mvc-routing

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!


Solution

  • 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"))