[英]How to create a link to switch language in ASP.NET Core 2.2?
A website supports several languages. 网站支持多种语言。 The code to support multi-language including the routes are already in place and working.
支持多语言(包括路线)的代码已经到位并且可以正常使用。
The localization is set up using the RouteDataRequestCultureProvider
as explaned at https://joonasw.net/view/aspnet-core-localization-deep-dive . 本地化使用
RouteDataRequestCultureProvider
设置,如https://joonasw.net/view/aspnet-core-localization-deep-dive所述 。
app.UseRouter(routes =>
{
routes.MapMiddlewareRoute("{culture=en-US}/{*mvcRoute}", subApp =>
{
subApp.UseRequestLocalization(localizationOptions);
subApp.UseMvc(mvcRoutes =>
{
// Routes are here
}
});
});
How to create a generic tag which will show the current page in a different language? 如何创建一个通用标签,以另一种语言显示当前页面?
Ideally, I would just specify which language this link should point to and that it should keep all other route parameters (like the current controller, the current action, the current route model) so I can have this link in the _Layout.cshtml
? 理想情况下,我只需要指定此链接应指向的语言,并保留所有其他路由参数(如当前控制器,当前操作,当前路由模型),即可在
_Layout.cshtml
使用此链接?
I managed to do this with the partial view for language dropdown list. 我设法通过语言下拉列表的局部视图来做到这一点。
RequestLocalizationOptions
to the partial view RequestLocalizationOptions
注入部分视图,首先获得受支持的区域性列表 Collect route data values and query string parameters as well into a dictionary, so if you have a link like below it will catch all parameters. 将路线数据值和查询字符串参数也收集到字典中,因此,如果您具有如下所示的链接,它将捕获所有参数。
/en-US/Products/?page=5&keyword=bla-bla-bla
/ zh-CN / Products /?page = 5&keyword = bla-bla-bla
Loop in the supported cultures to create links and replace {culture}
route value with the appropriate in the loop. 循环播放受支持的区域性以创建链接,并在循环中将
{culture}
路由值替换为适当的值。 The only thing to consider is to have {culture}
defined in the global route. 唯一要考虑的是在全局路径中定义
{culture}
。
here is my _Languages.cshtml
partial view: 这是我的
_Languages.cshtml
部分视图:
@using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options
@inject IOptions<RequestLocalizationOptions> LocOps
@{
var requestCulture = CultureInfo.CurrentCulture;
var supportedCultures = LocOps.Value.SupportedUICultures
.Select(c => new SelectListItem
{
Value = $"{c.Name}",
Text = $"{c.DisplayName}"
}).ToList();
var routeData = new Dictionary<string, string>();
foreach (var r in ViewContext.RouteData.Values)
{
routeData.Add(r.Key, r.Value.ToString());
}
foreach(var qs in Context.Request.Query)
{
routeData.Add(qs.Key, qs.Value);
}
}
<div class="dropdown">
<a class="btn-sm btn-default border border-secondary dropdown-toggle" href="#" role="button" id="dropdownLang" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
@($"{requestCulture.DisplayName}")
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownLang">
@foreach (var culture in supportedCultures)
{
if (culture.Value.ToLower() != requestCulture.Name.ToLower())
{
// replace {culture} value with the one from the list
routeData["culture"] = culture.Value;
<a class="dropdown-item small"
asp-all-route-data="@routeData">
@culture.Text
</a>
}
}
</div>
</div>
btw, I'm using bootstrap 4. 顺便说一句,我正在使用引导程序4。
I created a nuget package that creates a language navigation menu with one line of code :) 我创建了一个nuget包,该包使用一行代码创建了一个语言导航菜单:)
PM > Install-Package LazZiya.RazorLibrary -Version 1.0.1
<partial name="/Areas/LazZiya/Pages/_LanguageMenu.cshtml" />
compatible with .NetCote 2.1 or later and bootstrap 4 与.NetCote 2.1或更高版本以及Bootstrap 4兼容
culture
culture
I created a tag helper that supports all versions of current dotnet core frameworks to create a language navigation depending on supported cultures or manually selected list of cultures. 我创建了一个标记帮助程序,该程序支持当前dotnet核心框架的所有版本,以根据支持的区域性或手动选择的区域性列表创建语言导航。
install nuget package (it contains another useful tag helpers as well): 安装nuget软件包(它还包含另一个有用的标签助手):
Install-Package LazZiya.TagHelpers -Version 2.0.0
add tag helpers to _ViewImports.cshtml 将标签助手添加到_ViewImports.cshtml
@addTagHelper *, LazZiya.TagHelpers
Create the language naviation : 创建语言导航:
<language-nav view-context="ViewContext"></language-nav>
for more details visit project website , see live demos 欲了解更多详情,请访问项目网站 ,观看现场演示
This is not super elegant but it should do the trick. 这不是超级优雅,但应该可以解决。 Here as an example for en-US and de-DE only:
这里仅以en-US和de-DE为例:
var switchLang = new Dictionary<string, string>{{"de-DE", "en-US"}, {"en-US", "de-DE"}};
var controller = Html.ViewContext.RouteData.Values["controller"].ToString();
var action = Html.ViewContext.RouteData.Values["action"].ToString();
var lang = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
var newLang = lang;
switchLang.TryGetValue(lang, out newLang);
You can then use the variable controller, action and newLang to build an ActionLink to the other language. 然后,您可以使用变量控制器,action和newLang构建与另一种语言的ActionLink。 I just put a line into one of my _Layout.cshtml like to show the value of
我只是在我的_Layout.cshtml中放入一行以显示
var url = string.Format("{0}/{1}/{2}",newLang, controller, action);
And it looked OK. 而且看起来还不错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.