Robert Robert - 2 months ago 10
C# Question

How to add a parameter to the current URL in a view?

I have a web application based an ASP.NET MVC4 in which I use a layout that contains three language flags (images). These flags are visible throughout the whole site. Now I want to use these images for language selection. In order to show any of the pages in a specific language, I just need to add a parameter to the current URL and load it, my controllers then evaluate it and set the correct language in the model (or set a default fallback language when there's no language specified in the request).

Here's an example (hxxp = http):

No language specified:


Language specified:


My question is: how can I form a link in my layout that surrounds a language flag image and always points to the currently loaded URL with all the paramters PLUS a new parameter
in case there's only the language parameter?

In other words: how to create a link to the very same page with all parameters and simply add a route value to the URL?

Update: Here's a detailed example

In my
I have:

var u_eng = new RouteValueDictionary(Url.RequestContext.RouteData.Values);
var u_deu = new RouteValueDictionary(Url.RequestContext.RouteData.Values);
var u_por = new RouteValueDictionary(Url.RequestContext.RouteData.Values);
u_eng.Add("lang", "1033");
u_deu.Add("lang", "1031");
u_por.Add("lang", "1046");
<a href="@Url.RouteUrl(u_por)" class="Flag BR">BR</a>
<a href="@Url.RouteUrl(u_eng)" class="Flag US">US</a>
<a href="@Url.RouteUrl(u_deu)" class="Flag DE">DE</a>

Now, when I run the site, the links on the start page work just fine, they point towards the current page and add the lang=xy parameter to the corresponding URL.

But when I go to another page that uses the very same layout file and also uses a parameter, the links don't get build correctly: suppose I go to a subpage that is defined by this URL:


The page itself gets displayed correctly. But when I hover or follow the language links, they point to:

instead of


As you can see, any existing parameters are omitted.


You can use current route values collection, add new value to it, and then produce the url with url helper RouteUrl. To collect query string parameters passed to the page you can iterate throught the HttpContext.Request.QueryString dictionary:

    var currentRouteValues = new RouteValueDictionary(Url.RequestContext.RouteData.Values);
    var queryString = Request.QueryString;
    foreach (var key in queryString.AllKeys)
        currentRouteValues.Add(key, queryString[key]);

    currentRouteValues.Add("lang", "1033"); 

Then use it like this: