开发者

Dynamically adding a CSS file from an ASP.NET Server Control

开发者 https://www.devze.com 2022-12-27 02:46 出处:网络
I have a custom control and I want to dynamically insert a lin开发者_如何学Gok to a stylesheet.

I have a custom control and I want to dynamically insert a lin开发者_如何学Gok 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.


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>


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.


If you are dynamic css in head tag it wont work, you need to paste the css link tag in the body tag then it may work


I know this question have already accepted an answer. I recently went through the same error. The javascript/Css with <% %> tags from the head can give you error. Removing ASP tags <% %> from head fixes this error.

I was getting the same error in a weird way, I had css files in master page, It used to work for the first page but on the second page after redirecting, I was getting error. So I removed the css link from head tag and pasted it at the end of form tag.

http://italez.wordpress.com/2010/06/22/ajaxcontroltoolkit-calendarextender-e-strana-eccezione/

0

精彩评论

暂无评论...
验证码 换一张
取 消