Showing posts with label Embedded files MVC 3 Razor Views Image Javascript CSS. Show all posts
Showing posts with label Embedded files MVC 3 Razor Views Image Javascript CSS. Show all posts

Saturday 17 September 2011

Simple access of embedded resources in DLLs in MVC views

I was working with embedded views in a DLL in a MVC Razor 3 project today and I had to be able to refer to embedded Javascript .js files, images (jpg and png) and css files in the precompiled views. To make this work I tagged the files as Embedded Resource in my project, compiled the project into a dll and in the other mvc project which used the dll I could get it to fetch the embedded resources easily adding a new MVC controller action.

The mvc controller action looks like this:

The code below goes into the Home controller, ContentFile action method, which
returns a FileStreamResult below.



public FileStreamResult ContentFile(string id)
{
string resourceName = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList().FirstOrDefault(f => f.EndsWith(id));
return new FileStreamResult(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName), GetMIMEType(id));
}

private string GetMIMEType(string fileId)
{
if (fileId.EndsWith(".js"))
{
return "text/javascript";
}
else if (fileId.EndsWith(".css"))
{
return "text/stylesheet";
}
else if (fileId.EndsWith(".jpg"))
{
return "image/jpeg";
}
return "text";
}


To use this in the views, write this:



<script type="text/javascript" src="/Home/ContentFile/test.js">
</script>

<link rel="Stylesheet" href="/Home/ContentFile/blue.css">

<img src="/Home/ContentFile/forest.jpg" />



To load up an embedded resource we look into the executing dll, which instead should perhaps load a specified assembly if necessary, and then GetManifestResourceStream and retrieving the matching resource name passed in. The MIME type must be set and is resolved by looking at the resource name passed in.

So the morale is that if you want to load a content file from a DLL in a MVC view, use a controller action and return a FileStreamResult and then load up the content file by writing the route to the ContentFile action.