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:
User clicks on a link like @Html.ActionLink("English", ViewContext.RouteData.Values["Action"], ViewContext.RouteData.Values["Controller"], new { lang = "en-us"}, null)
You change the language in the controller's action method
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.