User control with external CSS file

I have an ASCX user control in the root directory of my web application. It refers to a stylesheet, something like

<link type="text/css" rel="stylesheet" href="MyStyle.css" /> 

The problem is that any ASPX pages that are in application subfolders refer to this user control - they don’t see the stylesheet because the href path is relative and the stylesheet remains in the root of the application.

Is there a way besides copying CSS to all subfolders for universal reference to it from the root? I have no problem linking to external JavaScript using ScriptManagerProxy. I can specify the path to the external JS file through ASP.NET notation "~ /", which will be resolved to the real path from anywhere. Does something like this exist for CSS?

+4
source share
4 answers

As I mentioned in my comments, I did not want to use <% =%> blocks. But I did not want to assign the URL of the CSS file in the code, so I found a compromise. I declare the <link> tag with the runat="server" attribute and href in ASP.NET style:

 <link rel="stylesheet" type="text/css" runat="server" id="xlinkCSS" href="~/MyStyle.CSS" /> 

and then in code for a simple solution that refers

 xlinkCSS.Attributes("href") = ResolveUrl(xlinkCSS.Attributes("href")) 

Using this approach, I can ultimately create a function that takes the page as a parameter, goes through all the "link" tags, resolving their URLs.

+6
source

ResolveUrl will convert 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 do not want to use the built-in code blocks

code for

 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"/> 
+5
source

In fact, you have two options:

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

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

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

then use it in the ASP code:

 <link type="text/css" rel="stylesheet" href="<%=basepath %>MyStyle.css" /> 
+1
source

You have to make a bundle.config file, and then you can use it in your code

-one
source

Source: https://habr.com/ru/post/1499732/


All Articles