Search code examples
asp.netasp.net-mvcglobalizationazure-storage

Why does Html.DisplayFor and .ToString("C2") not respect CurrentUICulture?


In my ASP.MVC 2.0 website I have the following setting in web.config:

<globalization uiCulture="da-DK" culture="en-US" />

When I try to display an amount in a view using Html.DisplayFor() or ToString("C2") I expected to get "kr. 3.500,00" (uiCulture) and not "$3,500.00" (culture).

<%:Html.DisplayFor(posting => posting.Amount)%>
<%:Model.Amount.ToString("C2")%>

If I explicit uses CurrentUICulture info it works as expected, but I don't want to do that everytime I need to display a number, date or decimal. And I also like to use DisplayFor, which doesn't support the IFormatProvider parameter.

<%:Model.Amount.ToString("C2", System.Globalization.CultureInfo.CurrentUICulture)%>

How can I change the formatting, without changing the culture of the system?

This is running in Azure, and if I change the culture to "da-DK" all decimal points are lost, when saving to Azure Table storage! #BUG


Solution

  • The UI culture is used to lookup and load resources, the Culture is used for formatting.

    So the various ToString(string) and String.Format overloads that don't take a culture will use the thread's current Culture (System.Globalization.CultureInfo.CurrentCulture) to format.

    If you want to use Danish formatting for currency, dates, ... then Thread.CurerentThread.CurrentCulture needs to be set to CultureInfo.GetCultureInfo("da-DK") (directly or indirectly).

    Summary: you have Culture and UI Culture the wrong way around.