Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET - How to include CSS only if it isn't already included?

I use the code bellow to dynamically include a CSS file:

HtmlHead head = (HtmlHead)Page.Header;
HtmlLink link = new HtmlLink();
link.Attributes.Add("href", Page.ResolveClientUrl("~/App_Themes/Default/StyleSheet.css"));
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
head.Controls.Add(link);

The problem is: I want to do it only once, and only if it isn't alrealy included in the page.

How do I verify if it is already included?

Edit:

Answers telling me to include in page load using !IsPostBack won't solve my problem, as this code will be inside a Web User Control and my page may have a lot of the same user control.

For example, I use the code below to do it with javascript:

if (!Page.ClientScript.IsClientScriptIncludeRegistered("jsScript"))
{
    Page.ClientScript.RegisterClientScriptInclude("jsScript", ResolveUrl("~/Utilities/myScript.js"));
}
like image 918
Tufo Avatar asked Mar 02 '10 20:03

Tufo


People also ask

How to import css in ASP net?

Drag and drop css below header file->then go to downloaded css template and open that template -> right click on the template and click the option "view page source" -> copy the template body code-> open the master page -> paste the template body code within the body of master page.

Can we use css in asp net?

ASP.NET Web pages function as HTML pages at run time. You can therefore use cascading style sheets (CSS) to set the appearance of any elements on the page other than Web server controls.


1 Answers

Did it...

the code I used is as follows:

        Boolean cssAlrealyIncluded = false;
        HtmlLink linkAtual;
        foreach (Control ctrl in Page.Header.Controls)
        {
            if (ctrl.GetType() == typeof(HtmlLink))
            {
                linkAtual = (HtmlLink)ctrl;

                if (linkAtual.Attributes["href"].Contains("datePicker.css"))
                {
                    cssAlrealyIncluded = true;
                }
            }
        }

        if (!cssAlrealyIncluded)
        {
            HtmlLink link = new HtmlLink();
            link.Attributes.Add("href", ResolveUrl("~/Utilities/datePickerRsx/datePicker.css"));
            link.Attributes.Add("type", "text/css");
            link.Attributes.Add("rel", "stylesheet");
            Page.Header.Controls.Add(link);
        }
like image 119
Tufo Avatar answered Sep 28 '22 02:09

Tufo