How to add Script in the Page <head></head> dynamically

筅森魡賤 提交于 2019-12-11 00:02:24

问题


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!


回答1:


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.




回答2:


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());
}
...



回答3:


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



来源:https://stackoverflow.com/questions/6928420/how-to-add-script-in-the-page-head-head-dynamically

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