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?

4

2 回答 2

2

您最终可能使用的是 Html.RouteLink()

在这种情况下,我会这样称呼它(如果需要多种语言,则更改为数组):

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

(记住新的 RouteValueDictionary(),你不想覆盖现有的)

接着:

@Html.RouteLink("English", enRoute)

这有点讨厌,如果不使用视图变量(我不喜欢)你就无法绕过它,但是你可以获得链接的整个路径。

于 2013-04-09T12:47:45.430 回答
0

使用此方法的内联方式:

@Html.ActionLink("English", this.ViewContext.RouteData.Values["controller"].ToString(), new RouteValueDictionary(ViewContext.RouteData.Values) {["language"] = "en"})
于 2016-03-09T20:14:55.693 回答