Add JQuery, Javascript, CSS to ASPx User Controls parent

Category : ASP.Net, C#, JQuery/JScript

This is my preferred method. (Microsoft has controls such as ScriptManager and ScriptManagerProxy but like nearly everything they do, I believe its overkill) To me, this is the simplest method.

The Problem: You want to convert or to create a user control that has scripts and/or css.

Solution: Within the Page_Load event of the user control, simply include the following:

    //For Scripts - notice we add this script call to the PARENT HEADER
    LiteralControl jQuery = new LiteralControl();
    jQuery.Text = "<script type=\"text/javascript\" src=\"js/jquery.js\"></script>";
    Page.Header.Controls.Add(jQuery);
 
    //For CSS - You could add Media under attributes as well.  
    HtmlLink stylesLink = new HtmlLink();
    stylesLink.Attributes["rel"] = "stylesheet";
    stylesLink.Attributes["type"] = "text/css";
    stylesLink.Href = "css/yourPagesCSS.css";
    Page.Header.Controls.Add(stylesLink);

Hope this helps someone! t

Post a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word