简体   繁体   中英

ASP.NET MVC generate url with different culture parameter by ActionLink

I have several url patterns as follows in the Route:

{lang}/package/{packageID}
{lang}/package/{packageID}/Edit/{partNumber}
...

There's a footer in layout.cshtml, the footer provides different culture links for users to change the language of the website. When the user click the link, I hope it can change the language and stay in the current page, so I render the link by Razor like this:

@Html.ActionLink("English", ViewContext.RouteData.Values["Action"], ViewContext.RouteData.Values["Controller"], new { lang = "en-us"}, null)
@Html.ActionLink("Traditional Chinese", ViewContext.RouteData.Values["Action"], ViewContext.RouteData.Values["Controller"], new { lang = "zh-tw"}, null)
@Html.ActionLink("Japanese", ViewContext.RouteData.Values["Action"], ViewContext.RouteData.Values["Controller"], new { lang = "ja-jp"}, null)
...

But there is a problem is that I need to pass other parameters which I mentioned above to the page accordingly to keep users staying in the current page.

How could I achieve in this scenario?

Thanks!

You may create an extension method as an helper for the creation of language-dependent links:

public static class LanguageExtensions
{
    public static RouteValueDictionary ForLang(this RouteValueDictionary dict, string lang)
    {
        var cloned = new RouteValueDictionary(dict);
        cloned["lang"] = lang;
        return cloned;
    }
}

Now you may use it in this way:

@Html.ActionLink("English", ViewContext.RouteData.Values["Action"], ViewContext.RouteData.Values["Controller"], ViewContext.RouteData.ForLang("en-us"), null)

You could use return Redirect(HttpContext.Request.UrlReferrer.ToString()); to return to take users back to the page they were at and not have to worry about passing the parameters again.

The flow would be:

  1. User clicks on a link like @Html.ActionLink("English", ViewContext.RouteData.Values["Action"], ViewContext.RouteData.Values["Controller"], new { lang = "en-us"}, null)

  2. You change the language in the controller's action method

  3. Take user back to the page they were on by calling return Redirect(HttpContext.Request.UrlReferrer.ToString()); from the same action method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM