用RegisterStartupScript注册脚本失效的解决方法

来源:互联网 发布:怎么能学好c语言 编辑:程序博客网 时间:2024/05/04 04:51
用RegisterStartupScript注册脚本失效的原因之一是没有将代码放到<form runat="server"></form>中间!!!

 

查阅MSDN,找到ClientScriptManager的用法:
ClientScriptManager.RegisterStartupScript 方法 (System.Type  type, String key , String script, BooleanaddScriptTags)
参数
type
要注册的启动脚本的类型。
key
要注册的启动脚本的键。
script
要注册的启动脚本文本。
addScriptTags
指示是否添加脚本标记的布尔值。
使用类型、键、脚本文本和指示是否添加脚本标记的布尔值向 Page 对象注册启动脚本。

 

下面的代码示例演示 RegisterStartupScript 方法的用法。请注意,addScriptTags 参数设置为 false,所以脚本开始标记和结束标记包含在 script 参数中。using System.Web.UI;

using System.Text;

<%@ Page Language="C#"%><script runat="server">  public void Page_Load(Object sender, EventArgs e)  {    // Define the name and type of the client scripts on the page.    String csname1 = "PopupScript";    String csname2 = "ButtonClickScript";    Type cstype = this.GetType();            // Get a ClientScriptManager reference from the Page class.    ClientScriptManager cs = Page.ClientScript;    // Check to see if the startup script is already registered.    if (!cs.IsStartupScriptRegistered(cstype, csname1))    {      String cstext1 = "alert('Hello World');";      cs.RegisterStartupScript(cstype, csname1, cstext1, true);    }    // Check to see if the client script is already registered.    if (!cs.IsClientScriptBlockRegistered(cstype, csname2))    {      StringBuilder cstext2 = new StringBuilder();      cstext2.Append("<script type=text/javascript> function DoClick() {");      cstext2.Append("Form1.Message.value='Text from client script.'} </");      cstext2.Append("script>");      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);    }  }</script><html>  <head>    <title>ClientScriptManager Example</title>  </head>  <body> <form id="Form1" runat="server">     <input type="text" id="Message"> <input type="button" value="ClickMe" onclick="DoClick()"> </form>  </body></html>


 

原创粉丝点击