Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to handle Embedded Resources on a Razor View?

I'm migrating some code from the ASPX view engine to Razor and I've run up onto a roadblock.

I have this code:

<link rel="Stylesheet" type="text/css" href="
    <%=Page.ClientScript.GetWebResourceUrl
        (typeof(DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector), 
        "DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector.css")%>" />

The problem here is that with Razor, I have no Page property.

So I took a step back for a second, and I'm looking at this wondering: What is the right way to get embedded resources in Razor?

I've spent a good bit of time trying to find solutions on this subject, but I haven't really found anything other than "wrap a new Page in a helper"

Is that the only way to do it? Or is there something more correct?

like image 549
Joseph Avatar asked Feb 14 '11 19:02

Joseph


People also ask

Which of the following are valid extensions for Razor view?

The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.

Why we use Razor View Engine in MVC?

It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML. It's just that ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML.


1 Answers

Unfortunately the web resources are quite tied to the webforms infrastructure and it is difficult to reuse them without it. So a bit hacky but you could write a helper:

public static class UrlExtensions
{
    public static string WebResource(this UrlHelper urlHelper, Type type, string resourcePath)
    {
        var page = new Page();
        return page.ClientScript.GetWebResourceUrl(type, resourcePath);
    }
}

and in your razor view:

<link rel="stylesheet" type="text/css" href="@Url.WebResource(typeof(DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector), "DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector.css")" />

Another possibility is to write a custom HTTP handler/controller which will read the embedded resource from the assembly and stream it to the response by setting the proper content type.

like image 132
Darin Dimitrov Avatar answered Sep 17 '22 23:09

Darin Dimitrov