Greg
Greg

Reputation: 8784

Conditionally Add External CSS/Javascript Links

I need to add links to the header of an ASPX page based on a server-side function being called from Page_Load() of the Master Page. The entire site is using the same Master Page.

What's the best way to do this?

An <asp:Literal> control in the <head>?

Upvotes: 0

Views: 2697

Answers (3)

Remy
Remy

Reputation: 12703

Maybe too late, but the approach below has the advantage, that the same script is never added twice.

public static void RegisterClientScriptInclude(Page page, string name, string url)
{
    Type cstype = page.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = page.ClientScript;

    // Check to see if the include script exists already.
    if (!cs.IsClientScriptIncludeRegistered(cstype, name))
    {
        cs.RegisterClientScriptInclude(cstype, name, page.ResolveClientUrl(url));
    }
}

Come in handy, if you add external javascript files from different user controls on a need basis.

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83356

I've had success doing things like this in the past.

<link rel="Stylesheet" type="text/css" href="<%= System.Configuration.ConfigurationManager.AppSettings["dhxStyle"] %>" />

Upvotes: 1

Saeed Neamati
Saeed Neamati

Reputation: 35832

There are many ways to do that:

  1. In your Page_Load method, access the header of your master page programmatically like:

    HtmlGenericControl style = new HtmlGenericControl("link");
    style.Attributes.Add("href", "path-to-your-style");
    style.Attributes.Add("rel", "stylesheet");
    style.Attributes.Add("type", "text/css");
    this.Page.Header.Controls.AddAt(0, style);
    
  2. Second way is to put runat='server' attribute on your conditional styles in head, and in your Page_Load method, turn their visibility on or off:

    <link type='text/css' rel='stylesheet' href='path-to-css-file' 
    runat='server' id='cssFile' />
    

    then in your Page_Load you have:

    if (conditionIsNotMet)
    {
        cssFile.Visible = false;
    }
    

Upvotes: 1

Related Questions