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?
The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With