4
votes

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?

4

4 Answers

7
votes

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"/>
7
votes

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.

1
votes

Actually you have two options:

1- to include it in your themes folder, then the asp.net framework will automatically include it in all pages using this theme

2- to add a public variable in your CS code that includes the path, then to use it in your code, as the following code:

public string basepath = "http://" + Request.Url.Authority + Request.ApplicationPath;

then to use it in ASP code:

<link type="text/css" rel="stylesheet" href="<%=basepath %>MyStyle.css" />
-2
votes

You should make bundle.config file and then you can use this in your code