Jan 08 2007

Step 3: Render to page header


As explained in step 2 we want to render the script src tags into the page:s <header> part. And be able to do it from wothin the specific page:s contentplaceholders.  

I have developed a control for that - JSIncludeControl and it uses some of the techniques described in these articles:


The code looks like this:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace JavaScriptServe
{
    [ToolboxData("<{0}:JSIncludeControl runat=server></{0}:JSIncludeControl>"),
    ParseChildren(true),
    PersistChildren(false)
    ]

    public class JSIncludeControl : Control
    {
        private bool m_Debug = true;
        [Bindable(true)]
        [Category("JQuery")]
        [DefaultValue(true)]
        [Localizable(true)]
        public bool DebugMode
        {
            get
            {
                return m_Debug;
            }

            set
            {
                m_Debug = value;
            }
        }

        private List<IncludeFile> m_Includes = new List<IncludeFile>();
        [
        Category("General"),
        NotifyParentProperty(true),
        PersistenceMode(PersistenceMode.InnerProperty),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content)
        ]
        public List<IncludeFile> IncludeFiles
        {
            get
            {
                return m_Includes;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            //Additional plugin includes...
            foreach (IncludeFile oPlug in IncludeFiles)
            {
                string sInclude2 = this.ResolveUrl(oPlug.Path);
                HtmlGenericControl Include2 = new HtmlGenericControl("script");
                //Include.ID = "JQueryASPNET";
                Include2.Attributes.Add("type", "text/javascript");
                Include2.Attributes.Add("src", sInclude2);
                this.Page.Header.Controls.Add(Include2);
            }

        }

 

        protected override void Render(HtmlTextWriter output)
        {
        }
    }

    [DefaultProperty("Path")]
    public class IncludeFile
    {
        private string m_strPath;

        [Editor(typeof(System.Web.UI.Design.UrlEditor)
                 , typeof(System.Drawing.Design.UITypeEditor))]
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("~/scripts/enternamehere.js")]
        [Localizable(true)]
        public string Path
        {
            get
            {
                return m_strPath;
            }

            set
            {
                m_strPath = value;
            }
        }

    }
}