1

I am trying to implement a language chooser which is visible on all pages.

My application currently has two routes:

routes.MapRoute(
    name: "EventDriven",
    url: "{language}/{eventid}/{controller}/{action}/{id}",
    defaults: new { language = "en", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{language}/{controller}/{action}/{id}",
    defaults: new { language = "en", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

And in my shared _layout.cshtml file I have the following action links:

@Html.ActionLink("English", ViewContext.RouteData.Values["action"].ToString(), new {language="en"})
@Html.ActionLink("Français", ViewContext.RouteData.Values["action"].ToString(), new {language="fr"})

The problem I am encountering is I want the {eventid} route segment preserved, but it's not applicable on every url.

On the home index page http://localhost/MySite/, the two action links are as follows:

English: http://localhost/MySite/
French: http://localhost/MySite/fr

Which is good, but on my interior page http://localhost/MySite/en/2/Donation the action links are:

English: http://localhost/MySite/en/2/Donation
French: http://localhost/MySite/fr/Donation

If I go to http://localhost/MySite/fr/2/Donation then the action links are:

English: http://localhost/MySite/en/Donation
French: http://localhost/MySite/fr/2/Donation

The problem is the change language action link does not contain the eventid 2 information.

How do I make it so both links contain the event and language information (and any other route parameters unforeseeable in the future) without having to program explicitly for them?

1
  • Your second map route needs en to be changed to fr for starters Commented Nov 30, 2012 at 2:53

2 Answers 2

2

What you might end up using is Html.RouteLink()

In this case I'd call it like this (changed to an array if multiple languages are required):

@{
   var enRoute = new RouteValueDictionary(ViewContext.RouteData.Values);
   enRoute["language"] = "en";
   ....
}

(remember the new RouteValueDictionary(), you don't want to overwrite the existing one)

and then:

@Html.RouteLink("English", enRoute)

It's a bit nasty and you can't get around it without using the view variable (which I dislike) but you get your whole route for the link.

Sign up to request clarification or add additional context in comments.

Comments

0

A inline way to use this method:

@Html.ActionLink("English", this.ViewContext.RouteData.Values["controller"].ToString(), new RouteValueDictionary(ViewContext.RouteData.Values) {["language"] = "en"})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.