locked
How to route to the selected language in Core MVC? RRS feed

  • Question

  • User991566988 posted

    Hi

    I've applied this topic for multilingual in mvc core 2.2 web app.:

    https://medium.com/swlh/step-by-step-tutorial-to-build-multi-cultural-asp-net-core-web-app-3fac9a960c43

    The example above is applied for none mvc core web app and I applied it for mvc one.

    firstly, I Installed the required packages:

        <PackageReference Include="LazZiya.ExpressLocalization" Version="4.0.0" />
        <PackageReference Include="LazZiya.TagHelpers" Version="4.0.1" />

    Then I created new folder 'LocalizationResources' with two new classes in it:

        public class ExpressLocalizationResource
        {
        }
        public class ViewLocalizationResource
        {
        }

    Then copied the resources files inside the folder from here: https://github.com/LazZiya/ExpressLocalizationSample/tree/master/ExpressLocalizationSampleProject/LocalizationResources

    Then configured Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        //Some code
                var cultures = new[]
                {
                    new CultureInfo("tr"),
                    new CultureInfo("ar"),
                    new CultureInfo("hi"),
                    new CultureInfo("en"),
                };
                services.AddMvc()
                     .AddExpressLocalization<ExpressLocalizationResource, ViewLocalizationResource>(
                     ops =>
                     {
                         ops.ResourcesPath = "LocalizationResources";
                         ops.RequestLocalizationOptions = o =>
                         {
                             o.SupportedCultures = cultures;
                             o.SupportedUICultures = cultures;
                             o.DefaultRequestCulture = new RequestCulture("en");
                         };
                     })
                     .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            }
    
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                 //Some code
    
                app.UseRequestLocalization();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
    
    

    Then _ViewImports.cs:

    @using MultiLang
    @using MultiLang.Models
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    
    @using System.Globalization
    
    @addTagHelper *, LazZiya.TagHelpers
    @addTagHelper *, LazZiya.ExpressLocalization

    Then added the method to HomeController:

            public IActionResult SetCultureCookie(string cltr, string returnUrl)
            {
                Response.Cookies.Append(
                    CookieRequestCultureProvider.DefaultCookieName,
                    CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cltr)),
                    new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
                );
    
                return LocalRedirect(returnUrl);
            }

    Then added the rtl.css and ltr.css to css folder then updated shared _Layout:

    @using System.Globalization
    @{
        var culture = CultureInfo.CurrentCulture.Name;
        var dirCss = CultureInfo.CurrentCulture.TextInfo.IsRightToLeft ? "rtl" : "ltr";
    }
    
        @*Some Code*@
    
        <link rel="stylesheet" href="~/css/site.css" />
        <link rel="stylesheet" href="@($"/css/{dirCss}.css")" />
    
        @*Some Code*@
    
                        <partial name="_LoginPartial" />
                        <language-nav cookie-handler-url="@Url.Action("SetCultureCookie", "Home", new { area="", cltr="{0}", returnUrl="{1}" })"></language-nav>

    Then localized Home/Index view:

        <div class="text-center">
            <h1 class="display-4" localize-content>Welcome</h1>
            <p localize-content>Learn about <a href='https://docs.microsoft.com/aspnet/core'> building Web apps with ASP.NET Core</a>.</p>
        </div>

    for now every thing is working fine but when I firstly run the app. it is shown in Turkish language. Then if I refreshed the default page, It is shown in English or Arabic!

    Then if I navigate to some language, the page is shown blank with the two letters at the last of the url for example '/ar'.

    Why? and how to solve please?

    Saturday, June 6, 2020 7:44 AM

Answers

  • User711641945 posted

    Hi ,

    Be sure that download the correct version like below:

    <PackageReference Include="LazZiya.ExpressLocalization" Version="4.0.0" />
    <PackageReference Include="LazZiya.TagHelpers" Version="4.0.1" />

    Create `SetCultureCookie` action in HomeController:

    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult SetCultureCookie(string cltr, string returnUrl)
        {
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cltr)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
            );
    
            return LocalRedirect(returnUrl);
        }
    }

    Change the `language-nav` in _Layout.cshtml:

    <language-nav cookie-handler-url="@Url.Action("SetCultureCookie","Home",new { area="", cltr="{0}", returnUrl="{1}" })"></language-nav>
    

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 8, 2020 8:07 AM

All replies

  • User-2054057000 posted

    Globalization and Localization is covered by MS docs https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-3.1

    I recommend you to use it as they are excellent. Do not use external packages as they are no good.  

    Saturday, June 6, 2020 5:39 PM
  • User991566988 posted

    Why? everything is working fine with me except this problem.

    I want the select language bar to deal like this when choosing a language (giving a url as shown at the bottom of the image):

    Sunday, June 7, 2020 5:50 PM
  • User711641945 posted

    Hi ,

    Be sure that download the correct version like below:

    <PackageReference Include="LazZiya.ExpressLocalization" Version="4.0.0" />
    <PackageReference Include="LazZiya.TagHelpers" Version="4.0.1" />

    Create `SetCultureCookie` action in HomeController:

    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult SetCultureCookie(string cltr, string returnUrl)
        {
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cltr)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
            );
    
            return LocalRedirect(returnUrl);
        }
    }

    Change the `language-nav` in _Layout.cshtml:

    <language-nav cookie-handler-url="@Url.Action("SetCultureCookie","Home",new { area="", cltr="{0}", returnUrl="{1}" })"></language-nav>
    

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 8, 2020 8:07 AM
  • User991566988 posted

    I've applied your suggestion. Thanks.

    I've edited the topic and refreshed it please see in again.

    I think the language navigation bar is returning the url correctly but with not successful language change!

    Monday, June 8, 2020 6:13 PM
  • User711641945 posted

    Hi musbah7@hotmail.com,

    Please do not copy the resource file,it would do not work.You need to create and write by yourself.You could firstly write a simple resource file to test if it is ok.

    And this should be another question.Please remember to mark the answer and post a new thread.

    Best Regards,

    Rena

    Tuesday, June 9, 2020 7:03 AM