Is there a System.Web.UI.ClientScriptManager method that registers scripts inside the <head> tag?

China☆狼群 提交于 2019-12-08 08:15:30

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);
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!