如何使用jQuery更改CurrentCulture

问题描述

我有一个jquery函数,可以检测下拉列表中的更改项。我想使用jquery更改CurrentCulture,以更改.net core中的LocalizatedValue,这是包含我的试用版的jquery方法

    $('#dropdownList li').find("a").click(function () {

        $('#dropdown-button').html($(this).html());
        $("#dropdown-button").val($(this).text());

        
        
        
        if (document.getElementById('dropdown-button').innerText === "Arab") {
            Globalization.locale("ar")
        } else if (document.getElementById('dropdown-button').innerText === "French") {
            Globalization.locale("fr")

        } else if (document.getElementById('dropdown-button').innerText === "English") {
            Globalization.locale("en")
        }
    });
}); 

在那里,我需要使用cs代码的当前文化信息

 private string GetString(string name)
        {
            var query = localization.Where(l => l.LocalizedValue.Keys.Any(lv => lv == CultureInfo.CurrentCulture.Name));
            var value = query.FirstOrDefault(l => l.Key == name);
            return value.LocalizedValue[CultureInfo.CurrentCulture.Name];
        }

解决方法

这是基于official docs的有效演示:

1。在根项目中创建SharedResource.cs

public class SharedResource
{
}

2。在SharedResource.fr.resx文件夹中创建Resources以添加资源。Resources文件夹位于根项目中。

enter image description here 3.查看:

@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Localization
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options
@inject IStringLocalizer<SharedResource> SharedLocalizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name,Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

<div title="@SharedLocalizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
    <form id="selectLanguage" asp-controller="Home"
          asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"
          method="post" class="form-horizontal" role="form">
        <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@SharedLocalizer["Language:"]</label>
        <select name="culture" onchange="this.form.submit();"
                asp-for="@requestCulture.RequestCulture.UICulture.Name"
                asp-items="cultureItems">
        </select>
    </form>
</div>
<h1>@SharedLocalizer["Home Page"]</h1>

4.HomeController:

public class HomeController : Controller
{
    [HttpPost]
    public IActionResult SetLanguage(string culture,string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
        );

        return LocalRedirect(returnUrl);
    }
}

5.Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");
    services.AddControllersWithViews()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();          
    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),new CultureInfo("fr")
        };

            options.DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US"),new CultureInfo("en-US"));
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
    });

}

public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
   
    var supportedCultures = new[] { "en-US","fr" };
    var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
        .AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures);

    app.UseRequestLocalization(localizationOptions);
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");
           
    });
}

结果:

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...