0

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>?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can this be used to add links to external JavaScript files? I've only ever used it to add raw JS code.
Yes, it can. RegisterClientScriptInclude is the key.
1

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;
    }
    

1 Comment

(1) snazzy, seems much cleaner than a Literal
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.