Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 633
James Becwar Avatar asked Feb 22 '23 02:02

James Becwar


1 Answers

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>"))
like image 61
competent_tech Avatar answered Feb 24 '23 15:02

competent_tech