Search code examples
asp.net-mvcglobalization

Set uiCulture automatically based on browser accept language


How I can set the culture of the ui automatically based on the users'browser? All I found about this is Globalize.culture("pt-BR"); But it sets pt-BR as default and I dont want set this by default! I want only set this if the user is pt-BR! How can I do this? And the validator methods, how can I set them for a specific culture?


Solution

  • In a ASP.NET MVC the web.config is the right place. There is a quick summary, the first snippet shows, how could be e.g. pt-BR culture forced

    <globalization 
        enableClientBasedCulture="false" 
        uiCulture="pt-BR" 
        culture="pt-BR" />
    

    If application is ready to accept the culture from the client (browser), settings should be

    <globalization 
        enableClientBasedCulture="true" 
        uiCulture="auto" 
        culture="auto" />
    

    The above setting will take a Language selected in client browser (e.g. cs-CZ in my case). If none is defined then system settings will be used. Final snippet shows, how to allow client to set and send intended culture, but in case that no Language is pre-selected, override the system setting with some other default value pt-BR

    <globalization 
        enableClientBasedCulture="true" 
        uiCulture="auto:pt-BR" 
        culture="auto:pt-BR" />
    

    Extended: culture settings for jQuery validator and numeric input

    Note: I am definitely not an expert in jQuery and globalization techniques. This is example how I do adjust validator to correctly process any numeric input

    razor View part (X() is a shortcut for new HtmlString()):

    var defaultThousandSeprator = "@X(culture.NumberFormat.NumberGroupSeparator)";
    var defaultDecimalSeprator = "@X(culture.NumberFormat.NumberDecimalSeparator)";
    

    jQuery part (custom methods for min and max)

    $.validator.addMethod("min", function (value, element, param)
    {
      var num = value.replace(RegExp(" ", "g"), "") // remove spaces
              .replace(RegExp('\\' + defaultThousandSeprator, "g"), "") // thousand separator
              .replace(RegExp("\\" + defaultDecimalSeprator, "g"), "."); // fix decimals
      return this.optional(element) || num >= param;
    });
    $.validator.addMethod("max", function (value, element, param)
    {
      var num = value.replace(RegExp(" ", "g"), "") // remove spaces
              .replace(RegExp('\\' + defaultThousandSeprator, "g"), "") // thousands
              .replace(RegExp("\\" + defaultDecimalSeprator, "g"), "."); // decimals
      return this.optional(element) || num <= param;
    });
    

    And then jQuery.validator evaluates input values for cs-CZ: 10 000,00 correctly as well as en-US: 10,000.00.