Localization in Blazor using bootstrap dropdown menu

Kuler Master 406 Reputation points
2024-02-28T16:24:01.7966667+00:00

I've seen tons of tutorials and blog posts but they all suggest a select control for changing a language. None of them explains how to implement localization using HREF. Could you give me at least hint or link, that would help me figure out how to change the language using <a href="de/page">German</a>? I have implemented everything regard the localization except this feature. Thank you

Developer technologies ASP.NET ASP.NET Core
Developer technologies .NET Blazor
Developer technologies ASP.NET Other
0 comments No comments
{count} vote

Accepted answer
  1. Anonymous
    2024-02-29T06:17:41.17+00:00

    Hi,@Kuler Master, I wrote a minimal example for Blazor Server Side based on this document: register the related server and add the middleware in program.cs:

    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents();
    builder.Services.AddLocalization();
    builder.Services.AddControllers();
    builder.Services.AddBlazorBootstrap();
    .........
    var supportedCultures = new[] { "en-US", "es-CL" };
    var localizationOptions = new RequestLocalizationOptions()
        .SetDefaultCulture(supportedCultures[0])
        .AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures);
    app.UseRequestLocalization(localizationOptions);
    app.MapControllers();
    
    
    

    Add a controller:

    [Route("[controller]/[action]")]
    public class CultureController : Controller
    {
        public IActionResult Set(string culture, string redirectUri)
        {
            if (culture != null)
            {
                HttpContext.Response.Cookies.Append(
                    CookieRequestCultureProvider.DefaultCookieName,
                    CookieRequestCultureProvider.MakeCookieValue(
                        new RequestCulture(culture, culture)));
            }
            return LocalRedirect(redirectUri);
        }
    }
    

    The CultureSelector component:

    @using System.Globalization
    @inject NavigationManager Navigation
    <Dropdown>
        <DropdownToggleButton Color="ButtonColor.Secondary"> Select your locale</DropdownToggleButton>
        <DropdownMenu>
            @foreach (var culture in supportedCultures)
            {
                if (CultureInfo.CurrentCulture.Name!=culture.Name)
                {
                    <DropdownItem Type="ButtonType.Link" To="@CultureUri[culture.Name]">@culture.DisplayName</DropdownItem>
                }
                else
                {
                    <DropdownItem Type="ButtonType.Button" Active=true>@culture.DisplayName</DropdownItem>
                }
            }
        </DropdownMenu>
    </Dropdown>
    @code
    {
        private CultureInfo[] supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("es-CL"),
        };
        private string redirecturi { get; set; }
        private Dictionary<string, string> CultureUri { get; set; } = new();
        protected override void OnInitialized()
        {
            redirecturi  = Uri.EscapeDataString(new Uri(Navigation.Uri)
                        .GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped));
            foreach (var culture in supportedCultures)
            {
                var cultureEscaped = Uri.EscapeDataString(culture.Name);
                CultureUri.Add(culture.Name, $"Culture/Set?culture={cultureEscaped}&redirectUri={redirecturi}");
            }
        }
    }
    
    
    

    Add the component to MainLayout component(Notice the component should be a static page here for you want to implement localization using href ):

    <main>         
        <div class="top-row px-4">
            <CultureSelector/>
        </div>
        <article class="content px-4">
            @Body
        </article>
    </main>
    

    Add required css/js files follow this document. modify Home component and add the resource files:

    @using Microsoft.Extensions.Localization
    @inject IStringLocalizer<Home> Loc
    <PageTitle>Home</PageTitle>
    <h1>@Loc["Hi"]</h1>
    Welcome to your new app.
    

    Now when I first see the component: User's image Select Spanish: User's image

    For Blazor WebAssembly,you could refer to this part of document


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.