ASP.NET Core Blazor globalization and localization states:
Blazor's
@bind
functionality performs formats and parses values for display based on the user's current culture.
The current culture can be accessed from theSystem.Globalization.CultureInfo.CurrentCulture property
.
The statement is true, but the problem is that, the culture has to be set just before it is used (or maybe each time the DOM is refreshed).
For demonstration I will use standard blazor counter application. Let's modify Counter.razor
@page "/counter"
@using System.Globalization;
<h1>Counter</h1>
<input type="text" @bind="currentDate" />
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private DateTime currentDate = DateTime.Now;
private int currentCount = 0;
private void IncrementCount() {
if (currentCount < 2) Utils.SetCCDateFormat();
currentCount++;
}
public class Utils {
public static void SetCCDateFormat() {
var cc = CultureInfo.CurrentCulture.Clone() as CultureInfo;
cc.DateTimeFormat.ShortDatePattern = "dd-yyyy-m";
CultureInfo.CurrentCulture = cc;
CultureInfo.CurrentUICulture = cc;
}
}
}
The result is:
- when the page is first rendered the text box contain date formatted by server default culture.
- when the button is pressed first and second time the date format is
dd-yyyy-m
I attempted to modify the date in OnAfterRender
, OnInitialized
without success. Only usable solution, I have found, is setting the format on the begging of razor markup.
@{Utils.SetCCDateFormat();}
Is there a way to modify CurrentCulture to become persistent in the blazor circuit?
Is the observed behavior correct or is it a bug?
Edit
What I have found so far
It is possible to set culture properties (CultureInfo.CurrentCulture
) in a middleware before the blazor endpoint is created and the changes are persistent for the circuit lifetime. When we modify CurrentCulture
in component lifecycle methods the change is only temporary (till the end of the method).
My understanding of the problem is
- When a circuit is created it stores the current culture somewhere
- A server has a limited number of threads
- A thread is assigned to a circuit when required and the current culture is set by what was stored at the beginning
- It is possible to modify the
CurrentCulture
, but this doesn't influence the setting storage and so when another event method is called (other thread) the original culture is used.
So it seems that the question is: How to modify the circuit culture settings when it is already created?
Maybe it is not possible and it is necessary do full refresh (start a request again with navigation) and use a middleware to set a modified culture. A culture storage existence is only my conjecture and I don't have any reference to support it.
Many thanks to Tyeth and Ashiquzzaman for help but I am not taking their attempts as the answer.