在madn上ClientScriptManager 类的示例:
1 <%@ Page Language="C#"%> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 <script runat="server"> 5 public void Page_Load(Object sender, EventArgs e) 6 { 7 // Define the name and type of the client scripts on the page. 8 String csname1 = "PopupScript"; 9 String csname2 = "ButtonClickScript"; 10 Type cstype = this.GetType();//当前页面的类型的获取 11 12 // Get a ClientScriptManager reference from the Page class. 13 ClientScriptManager cs = Page.ClientScript;//注意这儿ClientScriptManager对象的获取,ClientScriptManager是密封类,没有构造函数,不能实例化 14 15 // Check to see if the startup script is already registered. 16 if (!cs.IsStartupScriptRegistered(cstype, csname1)) 17 { 18 String cstext1 = "alert('Hello World');"; 19 cs.RegisterStartupScript(cstype, csname1, cstext1, true); 20 } 21 22 // Check to see if the client script is already registered. 23 if (!cs.IsClientScriptBlockRegistered(cstype, csname2)) 24 { 25 StringBuilder cstext2 = new StringBuilder(); 26 cstext2.Append("<script type=\"text/javascript\"> function DoClick() {"); 27 cstext2.Append("Form1.Message.value='Text from client script.'} </"); 28 cstext2.Append("script>"); 29 cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false); 30 } 31 } 32 </script> 33 <html xmlns="http://www.w3.org/1999/xhtml" > 34 <head> 35 <title>ClientScriptManager Example</title> 36 </head> 37 <body> 38 <form id="Form1" 39 runat="server"> 40 <input type="text" id="Message" /> <input type="button" value="ClickMe" onclick="DoClick()" /> 41 </form> 42 </body> 43 </html>
注意上面:
①使用RegisterStartupScript的情况下是不需要在待注册的脚本内容里面加上<script></script>了,而使用RegisterClientScriptBlock注册脚本代码块的时候就需要使用<script></script>否则将会导致加载到Page对象的脚本错误而无法执行
②使用Response.Write()方法,因为它会破坏页面的标准(会出现在页面的上方)
③注意页面类型的获取this.GetType
④注意ClientScriptManager对象的获取,ClientScriptManager是密封类,无法实例化