7

A website supports several languages. The code to support multi-language including the routes are already in place and working.

The localization is set up using the RouteDataRequestCultureProvider as explaned at https://joonasw.net/view/aspnet-core-localization-deep-dive.

app.UseRouter(routes =>
{
    routes.MapMiddlewareRoute("{culture=en-US}/{*mvcRoute}", subApp =>
    {
        subApp.UseRequestLocalization(localizationOptions);

        subApp.UseMvc(mvcRoutes =>
        {
             // Routes are here
        }   
    });
});

How to create a generic tag which will show the current page in a different language?

Ideally, I would just specify which language this link should point to and that it should keep all other route parameters (like the current controller, the current action, the current route model) so I can have this link in the _Layout.cshtml?

2
  • I don't think I fully understand this yet. Are you thinking of giving the user the ability to switch one page (temporarily) to a different language without changing the UIculture? If so, are you thinking of one specific language or shall that be dynamic in any fashion? Apr 2, 2019 at 11:55
  • No, the link should point to the current page/view just in a different language (in most cases, if the current page is /en-US/about, the link should point to /de-DE/about).
    – alik
    Apr 2, 2019 at 11:57

2 Answers 2

3

I managed to do this with the partial view for language dropdown list.

  • First get a list of supported cultures by injecting RequestLocalizationOptions to the partial view
  • Collect route data values and query string parameters as well into a dictionary, so if you have a link like below it will catch all parameters.

    /en-US/Products/?page=5&keyword=bla-bla-bla

  • Loop in the supported cultures to create links and replace {culture} route value with the appropriate in the loop. The only thing to consider is to have {culture} defined in the global route.

here is my _Languages.cshtml partial view:

@using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options

@inject IOptions<RequestLocalizationOptions> LocOps

@{
    var requestCulture = CultureInfo.CurrentCulture;

    var supportedCultures = LocOps.Value.SupportedUICultures

        .Select(c => new SelectListItem
        {
            Value = $"{c.Name}",
            Text = $"{c.DisplayName}"
        }).ToList();

    var routeData = new Dictionary<string, string>();

    foreach (var r in ViewContext.RouteData.Values)
    {
        routeData.Add(r.Key, r.Value.ToString());
    }

    foreach(var qs in Context.Request.Query)
    {
        routeData.Add(qs.Key, qs.Value);
    }
}

<div class="dropdown">
    <a class="btn-sm btn-default border border-secondary dropdown-toggle" href="#" role="button" id="dropdownLang" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        @($"{requestCulture.DisplayName}")
    </a>

    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownLang">
        @foreach (var culture in supportedCultures)
        {
            if (culture.Value.ToLower() != requestCulture.Name.ToLower())
            {
                // replace {culture} value with the one from the list
                routeData["culture"] = culture.Value;

                <a class="dropdown-item small"
                   asp-all-route-data="@routeData">
                    @culture.Text
                </a>
            }
        }
    </div>
</div>

btw, I'm using bootstrap 4.

UPDATE

I created a nuget package that creates a language navigation menu with one line of code :)

  • install nuget package
PM > Install-Package LazZiya.RazorLibrary -Version 1.0.1
  • create a language navigaton dropdown:
<partial name="/Areas/LazZiya/Pages/_LanguageMenu.cshtml" />

compatible with .NetCote 2.1 or later and bootstrap 4

  • notice : Route key name must be culture

UPDATE 2 (14.04.2019)

I created a tag helper that supports all versions of current dotnet core frameworks to create a language navigation depending on supported cultures or manually selected list of cultures.

install nuget package (it contains another useful tag helpers as well):

Install-Package LazZiya.TagHelpers -Version 2.0.0

add tag helpers to _ViewImports.cshtml

@addTagHelper *, LazZiya.TagHelpers

Create the language naviation :

<language-nav view-context="ViewContext"></language-nav>

for more details visit project website, see live demos


0

This is not super elegant but it should do the trick. Here as an example for en-US and de-DE only:

var switchLang = new Dictionary<string, string>{{"de-DE", "en-US"}, {"en-US", "de-DE"}};
var controller = Html.ViewContext.RouteData.Values["controller"].ToString();
var action = Html.ViewContext.RouteData.Values["action"].ToString();
var lang = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
var newLang = lang;
switchLang.TryGetValue(lang, out newLang);

You can then use the variable controller, action and newLang to build an ActionLink to the other language. I just put a line into one of my _Layout.cshtml like to show the value of

var url = string.Format("{0}/{1}/{2}",newLang, controller, action);

And it looked OK.

2
  • Yeah, that sounds really like an emergency hack :) I hope there is a more elegant/generic way to achieve that.
    – alik
    Apr 2, 2019 at 20:30
  • It might help if you defined more clearly what language link to use when and what default to use. Also how exactly language routing happens. Apr 2, 2019 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.