views:

45

answers:

1

I know it's strictly OK to put <script> tags in the body, but in the interest of neatness I'd like to use System.Web.UI.ClientScriptManager to register a script in the <head> of my page. Is there a method to accomplish this?

Thanks in advance.

+2  A: 

In these cases I usually add a ContentPlaceHolder in the tag of my Master Page.

Alternately I've used a method (usually in a utility class or PageBase class) that puts the script string in a List and stores it in the ASP.Net Context like so:

            List<string> javaScriptUrls = new List<string>();

            url = url.ToLower();

            javaScriptUrls = Context.Items[JS_KEY] as List<string>;

            if (javaScriptUrls == null)
            {
                javaScriptUrls = new List<string>();

                javaScriptUrls.Add(url);
            }
            else
            {
                if (!javaScriptUrls.Contains(url))
                    javaScriptUrls.Add(url);
            }

            Context.Items[JS_KEY] = javaScriptUrls;

Then OnPreRender of the MasterPage, it reads this List from the Context and builds tags in the header.

            List<string> _javaScript = Context.Items[JS_KEY] as List<string>;

            foreach (string js in _javaScript)
            {
                HtmlGenericControl script = new HtmlGenericControl();
                script.TagName = "script";
                script.Attributes.Add("type", "text/javascript");
                if (js.StartsWith("~/"))
                    script.Attributes.Add("src", head.ResolveUrl(js));
                else
                    script.Attributes.Add("src", js);

                head.Controls.Add(script);

                AddHeaderLineBreak(head);
            }
hunter
Thanks for the thorough answer. This workaround means I can't use "IsClientScriptIncludeRegistered"... I suppose you could just keep adding the urls to the list and then only register the unique entries.
Paul Suart
correct. Notice this line: if (!javaScriptUrls.Contains(url.ToLower())) javaScriptUrls.Add(url);That maintains uniqueness in the list
hunter