1. Automatically Use User-Culture
Have the user culture be set automatically on the current Thread/HttpContext
. In your Web.Config
:
<system.web>
...
<globalization enableClientBasedCulture="true" culture="auto" uiCulture="auto" />
...
</system.web>
2. Helper Function
Introduce a global method that will translate input text using the appropriate resource:
public static class Resources
{
public static string GetResource(string key, params object[] data)
{
if (String.IsNullOrEmpty(key))
return key;
// the actual call to your Resources
var res = Texts.ResourceManager.GetString(key.ToUpper(), Thread.CurrentThread.CurrentUICulture);
if (String.IsNullOrEmpty(res))
return data != null && data.Length > 0 ? String.Format(key.ToUpper(), data) : key;
if (data != null && data.Length > 0)
return String.Format(res, data);
return res;
}
}
The method also lets you pass an additional (optional) parameters to be used in a String.Format
way. For example:
// in your Resource file (Texts.es.resx)
GREETING_TEXT: "Hola amigo {0}, el tiempo es {1}"
// invocation
Resources.GetResource("GREETING_TEXT", "Chaim", DateTime.Now);
3. Controller Helper:
Introducing a _
methods that will let you translate texts quickly in the Controller:
public class BaseController : Controller
{
public string _(string key, params object[] data)
{
return Resources.GetResource(key, null, data);
}
}
In your controller you have to make sure you're inheriting your BaseController
and use it as follows:
public HomeController : BaseController:
{
public ActionResult GreetMe()
{
var msg = _("GREETING_TEXT", this.User, DateTime.Now);
return Content(msg);
}
}
4. Razor Helper
And for your Razor pages:
// non-generic version (for model-less pages)
public abstract class BaseWebPage : WebViewPage
{
public string _(string key, params object[] data)
{
return Resources.GetResource(key, null, data);
}
}
// generic version (for model defined pages)
public abstract class BaseWebPage<T> : WebViewPage<T>
{
public string _(string key, params object[] data)
{
return Resources.GetResource(key, null, data);
}
}
Now we have to set this new base WebPage as the base type for our pages in ~/Views/Web.Config
:
<system.web.webPages.razor>
...
<pages pageBaseType="Full.NameSpace.ToYour.BaseWebPage">
...
</system.web.webPages.razor>
(If you're using Areas, you'll have to modify each ~/Areas/AREA_NAME/Views/Web.Config
as well)
You can now use it in your Razor pages:
<h1>@_("HELLO")</h1>