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 likeLocalize(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 stati开发者_JAVA百科c 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?
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;
}
I use strongly typed resources using PublicResXFileCodeGenerator as Custom Tool (selected in properties of .resx file). If I have resource with 'AreYouSure' name and 'Are you sure?' value, it can be accessed by calling ResourceClass.AreYouSure
, both in controller and views. It works pretty well.
What do you want to localize in your controller? Normally only what is shown to the user should be localized. And what is shown to the user should be inside a view so back to the helpers.
精彩评论