Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Control with external CSS file

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?

like image 299
Yuriy Galanter Avatar asked Dec 11 '22 11:12

Yuriy Galanter


2 Answers

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"/>
like image 169
Lee Bailey Avatar answered Dec 25 '22 12:12

Lee Bailey


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.

like image 25
Yuriy Galanter Avatar answered Dec 25 '22 11:12

Yuriy Galanter