5

I use asp.net 4 and c#.

I have a Web User Control inside a Web From 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!

GibboK
  • 71,848
  • 143
  • 435
  • 658

3 Answers3

6

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.

joelmdev
  • 11,083
  • 10
  • 65
  • 89
  • I should mention that one of the crucial bits for adding anything to the head dynamically in server side code is adding runat="server" to your head element. – joelmdev Aug 03 '11 at 16:06
4

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">

nu everest
  • 9,589
  • 12
  • 71
  • 90
3

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());
}
...
George Johnston
  • 31,652
  • 27
  • 127
  • 172
  • Thanks Peter I understand, I still have a problem using within a MasterPage, the wired thing is from a web form with no master page the script is working fine, if there is a mp i'm not able to add in the ... any idea how to fix it? thanks for your time on this. – GibboK Aug 03 '11 at 15:08