Benvenuti da Idea R | Vicenza - Romano di Lombardia (Bergamo)

Blog

Prendere uno smanettone del software degli anni 80, aggiungere un graphic designer di nuova generazione e allungare il tutto con uno studioso di strategie di marketing. Agitare energicamente e si ottiene il blog Idea R.

How to include CSS files programmatically in ASP.NET

Pubblicato il 7/31/2012
Categorie: Siti Web
How to include CSS files programmatically in ASP.NET

ASP.NET gives you the opportunity to add script blocks and JavaScript includes at runtime using methods like ClientScriptManager.RegisterClientScriptInclude().

How to perform a similar action to include style sheets?

There's no native method, but it's quite simple to perform: we're going to use the HtmlLink control.

HtmlLink link = new HtmlLink();
link.Href = "./MyFolder/MyStyleSheet.css";
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(link);

An interesting parameter of the ClientScriptManager.RegisterClientScriptInclude() method is the Key, that's used to assure you do not add the same include twice.

How to perform the same thing with the previous code?
The solution is to give the control a unique id:

public void AddStyleLink(String Key, String StyleUrl)
{
    if (!String.IsNullOrEmpty(Key))
        if (Page.Header.FindControl(Key) != null) return;
 
    HtmlLink link = new HtmlLink();
    if (!String.IsNullOrEmpty(Key)) link.ID = Key;
    link.Href = StyleUrl;
    link.Attributes.Add("type", "text/css");
    link.Attributes.Add("rel", "stylesheet");
    Page.Header.Controls.Add(link);
}

 

newsletter

Did you like the article?

Subscribe to our free newsletter and stay up to date on digital strategies.

Sei il lettore numero 16,328.

Commenti

Articolo precedente

Articolo precedente

Infografica: il Social Media Marketing per il B2B

Articolo successivo

Campagne pubblicitarie interne con Google Analytics e AdRotator .NET

Articolo successivo