I have an ASCX user control in the root of my Web application. It references a stylesheet, something like
<link type="text/css" rel="stylesheet" href="MyStyle.css" />
The problem is if any ASPX pages located in application subfolders reference that user control - they don't see the stylesheet, because href path is relative and stylesheet remains in the app root.
Is there a way besides copying the CSS into all the subfolders to universally reference it from the root? I have no problem referencing external JavaScript, using ScriptManagerProxy I can specify path to external JS file via ASP.NET "~/" notation which gets resolved into real path from any location. Does something similar exist for CSS?
ResolveUrl will convert application-relative urls for you. http://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl.aspx
<link href="<%= ResolveUrl("~/MyStyle.css") %>" rel="stylesheet" />
EDIT: If you don't want to use inline code blocks
code-behind
protected void Page_Load(object sender, EventArgs e)
{
litStyle.Text = string.Format("<link href=\"{0}\" rel=\"stylesheet\" />", ResolveUrl("~/MyStyle.css"))
}
markup
<asp:Literal ID="litStyle" runat="server"/>
As I mentioned in my comments I didn't want to use <%= %> blocks. But I didn't want to assign URL of CSS file in code-behind either, so I found a compromise. I declare <link>
tag with runat="server"
attribute and ASP.NET - style href:
<link rel="stylesheet" type="text/css" runat="server" id="xlinkCSS" href="~/MyStyle.CSS" />
and then in code-behind simple resolve that link
xlinkCSS.Attributes("href") = ResolveUrl(xlinkCSS.Attributes("href"))
Using this approach ultimately I can create a function that accepts page as a parameter, loops thru all "link" tags, resolving their URLs.
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