0

I have a jquery function that detects changing items from dropdown List I want to change the CurrentCulture using jquery in order to change LocalizatedValue in .net core , that's the jquery method containing my trial version

    $('#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")
        }
    });
}); 

and there where I need the Current Culture Info in cs code

 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];
        }
Mahdi Guesmi
  • 68
  • 1
  • 8
  • Hi @Mahdi Guesmi,Did my answer help you resolve your issue?If so could you please accept as answer?if not,please follow up to let me know. – Rena Nov 18 '20 at 05:58

1 Answers1

0

Here is a working demo based on the official docs:

1.Create SharedResource.cs in the root project:

public class SharedResource
{
}

2.Create SharedResource.fr.resx in Resources folder to add the resources.Resources folder is in root project.

enter image description here 3.View:

@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?}");
           
    });
}

Result:

enter image description here

Rena
  • 30,832
  • 6
  • 37
  • 72