ASP.Net MVC Embedded Resource Helper Class
Getting embedded resources such as JavaScript, CSS and image files is a little bit more difficult when using the ASP.Net MVC framework as most of the useful methods for this will not work.
The only reliable way I have found it to invoke the GetWebResourceUrlInternal method via reflection on the assembly.
Note: I realise there are probably better ways of doing this but I posting this as a reminder to myself more than anything.
So, put your resources in the AssemblyInfo.cs folder as usual: (the following example is AssemblyName.Folder.File).
- [assembly: WebResource("MvcWebResourceTest.Resources.MyJavascriptFile.js", "test/javascript")]
You will need to add the following using statement System.Web.UI to the AssemblyInfo.cs file.
Note: make sure you’ve set the files Build Action property to Embedded Resource on the MyJavascriptFile.js.
You can then use the following class to generate the resource string to call in you’re html helpers, controllers etc.
- /// <summary>
- /// Helper class for getting embedded resources in ASP.Net MVC.
- /// </summary>
- public static class WebResourceHelper
- {
- const string GetWebResourceUrlInternal = "GetWebResourceUrlInternal";
- /// <summary>
- /// Gets the internal embedded resource url.
- /// </summary>
- /// <typeparam name="TAssemblyObject">
- /// Accepts an object that exists within the assembly containing the resources.
- /// </typeparam>
- /// <param name="resourcePath">Accepts a string resource path - assembly.folder.resource name</param>
- /// <returns>A string web resource url.</returns>
- public static string GetResourceUrl<TAssemblyObject>(string resourcePath)
- {
- MethodInfo getResourceUrlMethod = typeof(AssemblyResourceLoader)
- .GetMethod(GetWebResourceUrlInternal, BindingFlags.NonPublic | BindingFlags.Static);
- string resourceUrl = string.Format("/{0}", getResourceUrlMethod.Invoke
- (
- null,
- new object[] { Assembly.GetAssembly(typeof(TAssemblyObject)), resourcePath, false })
- );
- return resourceUrl;
- }
- }
An example call from a controller to add the resource to the view data collection could be something like the following:
- ViewData["ResourceUrl"] =
- WebResourceHelper.GetResourceUrl<HomeController>("MvcWebResourceTest.Resources.MyJavascriptFile.js");
Hope this is useful.
Kind Regards,
Sean McAlinden.