I would like to add localized strings in my view.
Resources/Views.Account.Login.en-US.resx
Views/Account/Login.cshtml
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
<div>
@System.Threading.Thread.CurrentThread.CurrentCulture.Name
@System.Threading.Thread.CurrentThread.CurrentUICulture.Name
@Localizer["Key"]
</div>
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var options = new RequestLocalizationOptions
{
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US")
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-US")
},
DefaultRequestCulture = new RequestCulture("en-US")
};
app.UseRequestLocalization(options);
}
The generated HTML
en-US
en-US
Key
The expected HTML
en-US
en-US
Hello
Have I forgotten a step?
EDIT
If the resources is named Resources/Views.Account.Login.resx
is work correctly. Why ?
you need to inject IStringLocalizer
use @inject IStringLocalizer<Your resources class name> _localizer;
in _ViewImports.cshtml
I have this code in ConfigureServices
var georgianCultureInfo = new CultureInfo("ka-GE");
var englishCultureInfo = new CultureInfo("en-US");
var russianCultureInfo = new CultureInfo("ru-RU");
var supportedCultures = new List<CultureInfo>
{
georgianCultureInfo,
englishCultureInfo,
russianCultureInfo
};
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture(georgianCultureInfo);
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
And this in Configure
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
您可以将键值对存储在Viewbag中并在jquery中使用$ .parse.JSON并遍历它并获取所需的值
Question:
If the resources is named Resources/Views.Account.Login.resx is work correctly. Why ?
Answer:
last part en-US
is for localization, if you omit it, that resource file will be chosen as default. localizer
is checking CurrentCulture
and then tries to find resource file with same ending part in name. if it couldn't find file, it will take default resource file.
Also try to remove parameter from services.AddLocalization(options => options.ResourcesPath = "Resources");
and left services.AddLocalization();
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.