Search code examples
asp.net-mvcmodel-view-controllerlocalizationinternationalization

How do you localize/internationalize an MVC Controller when using a SQL based localization provider?


Hopefully this isn't too silly of a question. In MVC there appears to be plenty of localization support in the views. Once I get to the controller, however, it becomes murky.

  • Using meta:resourcekey="blah" is out, same with <%$ Resources:PageTitle.Text%>.
  • ASP.NET MVC - Localization Helpers -- suggested extensions for the Html helper classes like Resource(this Controller controller, string expression, params object[] args). Similarly, Localize your MVC with ease suggested a slightly different extension like Localize(this System.Web.UI.UserControl control, string resourceKey, params object[] args)

None of these approaches works while in a controller. I put together the below function and I'm using the controllers full class name as my VirtualPath. But I'm new to MVC and assume there's a better way.

    public static string Localize (System.Type theType, string resourceKey, params object[] args) {
         string resource = (HttpContext.GetLocalResourceObject(theType.FullName, resourceKey) ?? string.Empty).ToString();
         return mergeTokens(resource, args);
    }

Thoughts? Comments?


Solution

  • I had the same question. This blogpost showed different ways to solve the problem: http://carrarini.blogspot.com/2010/08/localize-aspnet-mvc-2-dataannotations.html

    In the end I used a T4 template to generate a resources class. I also have a HtmlHelper method to access my resources:

    public static string TextFor(this HtmlHelper html, string resourceName, string globalResourceName, params object [] args)
    {
        object text = HttpContext.GetGlobalResourceObject(globalResourceName, resourceName);
        return text != null ? string.Format(text.ToString(), args) : resourceName;
    }
    

    Another version generates a localized version from Controller and View:

    public static string LocalTextFor(this HtmlHelper html, string resourceName, params object [] args)
    {
        string localResourceName = string.Format("{0}.{1}", html.ViewContext.RouteData.Values["controller"],
                                                     html.ViewContext.RouteData.Values["action"]);
        object text = HttpContext.GetGlobalResourceObject(localResourceName, resourceName);
        return text != null ? string.Format(text.ToString(), args) : langName;
    }