asp.net-mvcglobalization

How to globalize ASP.NET MVC views (decimal separators in particular)?


I'm working with the NerdDinner sample application and arrived at the section which deals with the Virtual Earth map. The application stores some values for the longitude and latitude. Unfortunately on my system floating point numbers are stored with a comma as the decimal separator, not a dot like in the US. So if I have a latitude of 47.64 it's retrieved and displayed as 47,64. Because that value is passed in a function call to the Virtual Earth API it fails at that point (e.g. JavaScript API expects 47.64, -122.13, but gets 47,64, -122,13).

I need to make sure that the application always uses dots. In a WebForms app I would have a common class which overrides the System.Web.UI.Page.InitializeCulture() method and I would be inheriting my pages from that class.

I am not sure about how to do the same with MVC. Do I need a customized ViewPage or something? Is there an easy way to solve this? Examples?


Solution

  • Because setting <globalization/> to en-US did not help at all I decided to create a custom class which initializes the proper culture settings and make sure that all views which require this behavior are inherited from my custom class.

    NerdDinnerViewPage.cs:

    using System.Globalization;
    using System.Threading;
    using System.Web.Mvc;
    
    namespace NerdDinner.Views
    {
        public class NerdDinnerViewPage<T> : ViewPage<T> where T : class
        {
            protected override void InitializeCulture()
            {
                base.InitializeCulture();
    
                Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentCulture.Clone() as CultureInfo;
    
                if (Thread.CurrentThread.CurrentCulture != null)
                {
                    Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator = ".";
                    Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
                }
            }
        }
    }
    

    Edit.aspx:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="NerdDinner.Views.NerdDinnerViewPage<NerdDinner.Models.DinnerFormViewModel>" %>