Dynamically adding a CSS file from an ASP.NET Serv

2019-02-09 15:43发布

I have a custom control and I want to dynamically insert a link to a stylesheet.

Might not be the best solution of the year but it needs to be done. Any idea how to do it?

Everytime I try, Page.Header is null.

2条回答
We Are One
2楼-- · 2019-02-09 16:00

To avoid the problem of multiple stylesheets when adding the control 10 times to the page, change the above code slightly:

string styleSheet = "stylesheetName.css";
if (this.Page.Header.FindControl(styleSheet) == null)
{
    HtmlLink cssLink = new HtmlLink();
    cssLink.ID = styleSheet;
    cssLink.Href = "~/styles/" + styleSheet;
    cssLink.Attributes.Add("rel", "stylesheet");
    cssLink.Attributes.Add("type", "text/css");
    this.Page.Header.Controls.Add(cssLink);
}

By giving the control an ID you can check if it already exists, and so ensure that you only add it the once.

查看更多
干净又极端
3楼-- · 2019-02-09 16:04

Here's how you would normally add a CSS programatically:

protected void Page_Init(object sender, EventArgs e)
{
    var link = new HtmlLink();
    link.Href = "~/styles/main.css";
    link.Attributes.Add("rel", "stylesheet");
    link.Attributes.Add("type", "text/css");
    Page.Header.Controls.Add(link);
}

You might need to put a runat="server" in the head tag:

<head runat="server">
    <title>Add CSS example</title>
</head>
查看更多
登录 后发表回答