Accessing Embedded Resources from Razor Views in ASP.Net MVC

In razor, there is no access to the ClientScriptManager so there is no readily available method of using that class’s useful GetWebResourceUrl method to retrieve embedded resources. There are few techniques for synthesizing the functionality, revolving around the reflection of the AssemblyResourceLoader class which is all fine and well unless the application trust level prohibits reflection of non-public members. A simpler and pragmatic method is to have a partial view of the old ascx variety, and have it access the ClientScript manager of it’s Page property as below:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<script 
     src="<%=Page.ClientScript.GetWebResourceUrl(typeof(Page), "WebForms.js")%>" 
     type="text/javascript"></script>

Note I’m referencing WebForms.js because I’m momentarily insane. I wouldn’t recommend it in practice !! ;-). To include this web resource in a razor layout page is the same as for any partial view:


<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script 
        src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" 
        type="text/javascript"></script>
    <!-- render using as ascx control to access the client script manager -->
    @{Html.RenderPartial("WebResources");}
</head>

And that’s all there is to it. Using this technique enable to continue using embedded resources from within your razor views.

Advertisements
This entry was posted in Razor and tagged , . Bookmark the permalink.

One Response to Accessing Embedded Resources from Razor Views in ASP.Net MVC

  1. Leonardo says:

    VERY, VERY, VERY GOOD!!!!!! THANKS MAN.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s