Page.Header.Controls.Add(control) is adding controls to <body> not <head>

倾然丶 夕夏残阳落幕 提交于 2019-12-12 12:11:00

问题


I'm trying add some code at run time to the head element. When I do this in the page load of a user control in the page:

HtmlGenericControl hc = new HtmlGenericControl();
hc.InnerHtml = GetParameter("HeaderCode");
Page.Header.Controls.Add(hc);

The control ends up in the body tag, as the first child element. For Example:

...
</head>
<body>
<span><meta>Test</meta></span>
...

From my understanding, the Page.Header is supposed to be the Head element. In the aspx page, the head has the runat="server" attribute set.

Any idea how I can inject a string in to the <head> element?


回答1:


The head element may have restrictions on the type of content. When we inject javascript into the header, we do it using a LiteralControl.

For example:

Page.Header.Controls.Add(New LiteralControl("<script language='javascript' type='text/javascript'>alert('test');</script>"))



回答2:


Try below code to add javascript, css or any other resources such as meta tags. I have successfully implemented this code on my website :

HtmlGenericControl my_js = new HtmlGenericControl("script");
            my_js.Attributes["async"] = "async";
            my_js.Attributes["type"] = "text/javascript";
            my_js.Attributes["src"] = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
            Page.Header.Controls.Add(my_js);

You need to use namespace : "using System.Web.UI.HtmlControls" to use HtmlGenericControl.



来源:https://stackoverflow.com/questions/8537571/page-header-controls-addcontrol-is-adding-controls-to-body-not-head

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