Asp.net core 多语言下拉列表还原为默认选择
好的,我现在有了语言,它正在为下拉列表中选择的语言选择合适的语言。但是,下拉列表不会记住正在写入cookie的所选语言,但会返回默认值。 我发现微软官方文档在这个细节上非常缺乏,我使用的是管理lte主题 SelectLanguage.HtmlAsp.net core 多语言下拉列表还原为默认选择,asp.net-core,Asp.net Core,好的,我现在有了语言,它正在为下拉列表中选择的语言选择合适的语言。但是,下拉列表不会记住正在写入cookie的所选语言,但会返回默认值。 我发现微软官方文档在这个细节上非常缺乏,我使用的是管理lte主题 SelectLanguage.Html @using Microsoft.AspNetCore.Builder @using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.Extensions.Options @inject IV
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options
@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultureItems = LocOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.NativeName })
.ToList();
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="languageDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
@Localizer["Language"]
</a>
<div class="dropdown-menu" aria-labelledby="languageDropdown">
@foreach (var language in @cultureItems)
{
<a class="dropdown-item" asp-controller="Home" asp-action="SetLanguage" asp-route-culture="@language.Value" asp-route-returnUrl="@returnUrl">@language.Text</a>
}
</div>
</li>
在我的家庭控制器中,我设置了以下内容
public HomeController(ILogger<HomeController> logger, IStringLocalizer<HomeController> localizer)
{
_logger = logger;
_localizer = localizer;
}
公共家庭控制器(ILogger记录器、IStringLocalizer定位器)
{
_记录器=记录器;
_定位器=定位器;
}
这是我的创业课
namespace RoundTableMVCore31
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("fr") };
options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders = new List<IRequestCultureProvider>
{
new QueryStringRequestCultureProvider(),
new CookieRequestCultureProvider()
};
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
services
.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var supportedCultures = new string[] { "en-GB", "fr-FR" };
app.UseRequestLocalization();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{culture=en-gb}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
名称空间圆桌会议MVCore31
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.MinimumSameSitePolicy=SameSiteMode.None;
});
AddLocalization(options=>{options.ResourcesPath=“Resources”;});
配置(选项=>
{
var supportedCultures=new[]{new CultureInfo(“en”)、new CultureInfo(“fr”)};
options.DefaultRequestCulture=新的RequestCulture(区域性:“en”,uiCulture:“en”);
options.SupportedCultures=SupportedCultures;
options.supportedCultures=supportedCultures;
options.RequestCultureProviders=新列表
{
新建QueryStringRequestCultureProvider(),
新CookiierRequestCultureProvider()
};
});
services.AddDbContext(选项=>
options.UseSqlServer(
GetConnectionString(“DefaultConnection”);
services.AddDefaultIdentity(options=>options.SignIn.RequireConfirmedAccount=true)
.AddEntityFrameworkStores();
services.AddControllersWithViews();
services.AddRazorPages();
服务
.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.后缀);
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
var-supportedCultures=新字符串[]{“en-GB”,“fr-fr”};
app.UseRequestLocalization();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{culture=en gb}/{controller=Home}/{action=Index}/{id?}”);
endpoints.MapRazorPages();
});
}
}
}
此外,如何包括国旗有一个标准的方式这样做
下拉列表不会记住正在写入cookie的所选语言,但会返回默认值
如果要在更改选定语言后保持下拉列表中选定项的“活动””状态,可以根据cookie的值为选定项动态指定.Active
CSS类,如下所示
在_Layout.cshtml文件中
$(函数(){
var cl=getCookie(“.AspNetCore.Culture”);
如果(cl!=“”){
var c=cl.split(“|”)[0]。子字符串(2);
//控制台日志(c);
$(“#lan items a.active”).removeClass(“active”);
//你的代码逻辑在这里
开关(c){
案例“fr”:
var atag=$(“#lan项目a.dropdown-item”)[1];
$(atag).addClass(“活动”);
打破
案例“en”:
var atag=$(“#lan项目a.dropdown-item”)[0];
$(atag).addClass(“活动”);
打破
}
}
})
函数getCookie(cname){
变量名称=cname+“=”;
var decodedCookie=decodeURIComponent(document.cookie);
var ca=decodedCookie.split(“;”);
对于(变量i=0;i
指定id为“lan项”的下拉菜单div
@foreach(@cultureItems中的var语言)
{
谢谢,ms文档中没有这一步,我相信应该添加这一步。只是想知道如何添加lanugage标志,这是可能的吗
namespace RoundTableMVCore31
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("fr") };
options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders = new List<IRequestCultureProvider>
{
new QueryStringRequestCultureProvider(),
new CookieRequestCultureProvider()
};
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
services
.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var supportedCultures = new string[] { "en-GB", "fr-FR" };
app.UseRequestLocalization();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{culture=en-gb}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
<script>
$(function () {
var cl = getCookie(".AspNetCore.Culture");
if (cl != "") {
var c = cl.split('|')[0].substring(2);
//console.log(c);
$("#lan-items a.active").removeClass("active");
//your code logic here
switch (c) {
case "fr":
var atag = $("#lan-items a.dropdown-item")[1];
$(atag).addClass("active");
break;
case "en":
var atag = $("#lan-items a.dropdown-item")[0];
$(atag).addClass("active");
break;
}
}
})
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
<div class="dropdown-menu" id="lan-items" aria-labelledby="languageDropdown">
@foreach (var language in @cultureItems)
{
<a class="dropdown-item" asp-controller="Home" asp-action="SetLanguage" asp-route-culture="@language.Value" asp-route-returnUrl="@returnUrl">@language.Text</a>
}
</div>