How to add Script in the Page <head></head> dynamically
I use asp.net 4 and c#.
I have a Web User Control inside a Web Fro开发者_如何转开发m page. When I include the Web User Control I would like also include programmatically some script within the tags for the final generated page.
Any idea how to do it? Maybe ScriptManager could help on this?
Please provide me a sample of code I'm pretty new at developing thanks for your time on this!
Peter's answer will add to the page, but not the head element. Take a look at this article:
http://weblogs.asp.net/johnkatsiotis/archive/2008/08/08/add-scripts-to-head-dynamically.aspx
It provides a nice clean way to add a script to the head element using an extension method.
I realize that this is an old question, but there is a much simpler way.
Try This:
Page.Header.Controls.Add(
new LiteralControl(
"<script>alert('Literal Added to <Head>.');</script>"
)
);
If you want to add the script at a particular index of the <head>
you can use
AddAt(index, new LiteralControl(...))
where index 0 equals the top of the <head>
Also, joelmdev mentioned in a comment you need to add runat="server"
in your head tag e.g. <head id="head1" runat="server">
Take a look at RegisterClientScriptBlock of the ClientScriptManager.
From MSDN:
...
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> function DoClick() {");
csText.Append("Form1.Message.value='Text from client script.'} </");
csText.Append("script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
...
精彩评论