30 April 2011

ASP.NET / MVC - Localization

Here's how I localized an ASP.NET MVC3 application.

The controller

the master layout page contained some language links like this one:

@Html.RouteLink("Nederlands",
                 new { Controller = "Home",
                       Action = "Language",
                       culture = "nl-BE" })

They refer to a simple action:

public ActionResult Language(string culture) {
  App.SetCulture(culture);
  return RedirectToAction("Index");
}

The model

I prefer handling the actual setting of the culture in the model, so I created a static class called App containing these methods:

public static void Store(string key, object value) {
  if (HttpContext.Current.Session != null)
    HttpContext.Current.Session[key] = value;
}

public static object Retrieve(string key) {
  return HttpContext.Current.Session == null ?
         null :
         HttpContext.Current.Session[key];
}

public static void SetCulture(string cultureName) {
  Store("culture", cultureName);
  Thread.CurrentThread.CurrentCulture =
  Thread.CurrentThread.CurrentUICulture =
  CultureInfo.GetCultureInfo(cultureName);
}

Very important: the thread culture must be set again for every request. But a .css file or image files are also a requests. For those requests however, the session object does not exist. Hence, the null-tests.

Global.asax

So the culture must be set for each request. You could do it in the Initialize method of each controller, or in just one place: Global.asax. I put it in the Application_AcquireRequestState method, because from this method on the session object is available. From there, it's just a simple call:

App.SetCulture((string)App.Retrieve("culture") ?? "nl-BE");

No comments:

Post a Comment