The Razor view engine shipped with ASP.NET MVC 3 is very clean and has some nice coding enhancements, see a introduction on Scott Gu’s blog. As I was converting a application over to use the new view engine, I was stumped to find that the global/local resource method was not directly accessible as it was with the default view engine. In order to access a resource you would have to type the following expression ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey) which is quite length. To mitigate this, I create some common extensions to clean up the code. Below shows a clean way of doing this.
public static class CommonHtmlExtensions
{
public static object GetGlobalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey)
{
return htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey);
}
public static object GetGlobalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey, CultureInfo culture)
{
return htmlHelper.ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey, culture);
}
public static object GetLocalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey)
{
return htmlHelper.ViewContext.HttpContext.GetLocalResourceObject(classKey, resourceKey);
}
public static object GetLocalResource(this HtmlHelper htmlHelper, string classKey, string resourceKey, CultureInfo culture)
{
return htmlHelper.ViewContext.HttpContext.GetLocalResourceObject(classKey, resourceKey, culture);
}
}
@Html.GetGlobalResource("CommonText", "Some_ResourceKey")