ASP.NET MVC Razor View Engine and Resources

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);
}

}
 
In the view you will have consolidate resource calls.  Hopefully they will add something like this in the future of ASP.NET MVC.
 
@Html.GetGlobalResource("CommonText", "Some_ResourceKey")

1 comment:

jimmy said...

Hi Tyson,

Thanks for posting this. I am writing a multi-lingual web app for a non-profit, and I am also considering using the Razor view engine. This is my first effort in C# and ASP.NET, so I would like to follow your suggestion, but need a little help.

Where are you using CommonHtmlExtension? I assume in the Controller, but can you reach those classes from the cshtml file? If so, how do you do that? How do I make a C# class available to Razor?

If you're using these at the controller level, are you populating ViewBag, or is there simpler way to do it?

Thanks for posting this; it gives me something to think about.

-Jimmy