问题
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