ASP.Net Culture
Every executing .Net thread has two important properties.- Thread.Culture
- Thread.CurrentUICulture
Thread.Culture
Impacts formatting of dates and numbers. For example:DateTime.Now.ToString(); // how is date displayed, month first, day first, etc.
date.ToShortDateString(); // format date appropriate for the culture
// what currency symbol is shows; what is 1000s separator
// decimal separator; 10.00 E (in euros)
amount.ToString(“c”);
Thread.CurrentUICulture
- Impacts loading of resources, such as strings
- Use Resources.resx to Localize the strings being displayed. For example, Strings.resx will store default resources.
- Resx files can store localized text and binary assets
- Create a Resource for each language you wish to support. For example, String.es.resx will store resource for Spanish culture
- Resource Loader loads the current resources for the culture
- In Visual Studio, set the BuildAction to embedded resource
- Visual Studio generates strongly-typed classes for Resource access
- Resources.Greeting returns culture specific string; falls back to base resources if no culture specific resource is present
Setting Culture in ASP.NET using HTTP headers
- Default language of the browser is passed in the accept-language header
- To turn on, refer to the <globalization> section of web.config
<system.web>
<globalization culture=”auto” uiCulture=”auto” />
</system.web>
Testing formatting based on accept-language header
- Go to Settings for Internet Explorer
- Internet Options
- Under appearance press [Languages]
- Pick a language
Manually Setting Culture in ASP.NET
- For example, user can select the language on the log in page
- Use CultureInfo::DefaultThreadCurrentCulture to set desired culture before using formatting classes and methods
Referencing resources in MVC
In Data Model using Data Annotation
[Required(ErrorMessageResourceType=type(<namespace>.MyResources),ErrorMessageResourceName=”UserNameRequiredError”]
public string username {get; set;}
In Razor View
1. Create Resource files. The resource files can be created in the same Web project, a Separate Library, or a separte folder in the Web project.2. Create MyResources.resx
Greeting: Welcome
3. Change access modifier to public from Internal so that the Razor views can use it since Razor views are compiled to a different assembly.
4. Add MyResources.fr.resx
Greeting: Bonjour!
For the localized resource, no code generation. Only done for the base resource file.
5. Modify view to use the resources
<h1>@<namespace>.MyResources.Greeting</h2>
This will load the correct string based on appropriate language accept header.
We can also create resources within the View subfolder and use in the View.
In Cached controller action
// Returns language-specific CACHED data// Adjust cache settings to vary by language
[OutputCache ... VarByHeader=”Accept-Language”)]
Controller
Can also use as follows in controllerViewBag.Message = MyResources.Greeting;