Skip to main content
All docs
V23.2

Localization and Globalization for Blazor WebAssembly

  • 4 minutes to read

Follow the steps below to localize a Dashboard component into different languages and cultures in a Blazor Server Application. This guide targets .NET 6.

View Example: Dashboard for Blazor WebAssembly - Localization

Localization is a process of translating UI element captions to another language: dialog boxes, buttons, menu items, error messages, and so on.

Globalization is a process of formatting dates, numbers, and currencies according culture-specific assumptions.

Use JSON files both for localization (localize the UI) and globalization (localize dates, numbers, and currencies).

Localization

Follow the steps below to localize a Dashboard component in a Blazor WebAssembly Application.

Important

Note that since the Web Dashboard exports data on the server side, add satellite resource assemblies to your project to complete the localization process.

Download JSON Files

Unpack a self-extracting archive and extract json resources. Create the wwwroot/localization/de directory, and add the dx-analytics-core.de.json and dx-dashboards.de.json files to it.

Note

If the Text Editor functionality is enabled, you also need to localize the Rich Text Editor: Rich Text Editor - Localization.

Load Localization Strings

In the client application, implement the IDashboardLocalizationProvider as a singleton service so that service reads and returns the localized JSON strings.

using DevExpress.DashboardWeb;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace BlazorDashboardApp.Client {
    public class DashboardWasmLocalizationProvider : IDashboardLocalizationProvider {
        static string[] GetJsonList() {
            switch (CultureInfo.CurrentUICulture.TwoLetterISOLanguageName) {
                case "de":
                    return new string[] {
                            "./localization/de/dx-dashboard.de.json",
                            "./localization/de/dx-analytics-core.de.json"
                    };
                default:
                    return new string[] { };
            }
        }

        IServiceProvider serviceProvider;

        public DashboardWasmLocalizationProvider(IServiceProvider serviceProvider) {
            this.serviceProvider = serviceProvider;
        }


        async Task<Dictionary<string, string>> ReadFileAsync(HttpClient httpClient, string fileName) {
            var httpRes = await httpClient.GetAsync(fileName);
            if (httpRes.StatusCode == HttpStatusCode.NotFound) {
                return new Dictionary<string, string>();
            }
            var response = await httpRes.Content.ReadAsByteArrayAsync();
            return JsonSerializer.Deserialize<Dictionary<string, string>>(response);
        }

        public async Task<Dictionary<string, string>> GetLocalizationMessagesAsync() {
            using (IServiceScope scope = serviceProvider.CreateScope()) {
                HttpClient? httpClient = scope.ServiceProvider.GetService<HttpClient>();
                var jsons = await Task.WhenAll(GetJsonList().Select(fileName => ReadFileAsync(httpClient, fileName)));
                return jsons.SelectMany(dict => dict).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            }
        }
    }
}

In the client’s Program.cs file, register this service as a singleton service:

builder.Services.AddSingleton<IDashboardLocalizationProvider>(sp => new DashboardWasmLocalizationProvider(sp));

Localize the Specified String at Runtime

You can also localize the specified string at runtime. Handle the DashboardControlOptions.onInitializing event and call the ResourceManager.setLocalizationMessages static method. In the index.html file, pass the string identifier and its values as the method’s parameter:

<script>
    window.dashboardEvents = {
        onInitializing: (args) => {
            // Localize the specified string at runtime (the "Export To" button's caption in the dashboard title):
            DevExpress.Dashboard.ResourceManager.setLocalizationMessages({ "DashboardStringId.ActionExportTo": "Custom Text for Export Button" });
            // ...
        }
    }

See the following topic for more information about how to apply JavaScript customization to a Dashboard component in Blazor: JavaScript Customization of Dashboard Component.

Globalization

The Dashboard component for Blazor uses Intl to apply culture-specific formatting. Intl is the short name used to refer to a particular ECMAScript Internationalization API object. The Web Dashboard supports this API out of the box. All you need to do is configure the culture on the client.

You can implement a UI that allows users to change the culture at runtime. The following example shows how to save the current culture in a cookie:

View Example: Dashboard for Blazor WebAssembly - Localization

window.blazorCulture = {
    get: () => window.localStorage['BlazorCulture'],
    set: (value) => window.localStorage['BlazorCulture'] = value
};
window.blazorUICulture = {
    get: () => window.localStorage['BlazorUICulture'],
    set: (value) => window.localStorage['BlazorUICulture'] = value
};

Apply Custom Formatting for Numbers and Dates

You can use Globalize to apply custom formatting for Numbers and Dates. Handle the DashboardControlOptions.onInitializing event and specify formatting:

window.dashboardEvents = {
    onInitializing: (args) => {
    // ...
        // Apply custom formatting for numbers and dates:
        var json = { main: {} };

        json["main"]["de"] = {
            numbers: { "currencyFormats-numberSystem-latn": { standard: "C #,##0.00 ¤" } },
            dates: { calendars: { gregorian: { dateTimeFormats: { availableFormats: { yMd: "dd MMM y" } } } } }
        };
        Globalize.load(json);
    }
}

See the following topic for more information about how to apply JavaScript customization to a Dashboard component in Blazor: JavaScript Customization of Dashboard Component.

See Also