使用Page.ClientScript.RegisterClientScriptBlock

来源:互联网 发布:mac散热器 编辑:程序博客网 时间:2024/04/29 06:00

19.10.1 使用Page.ClientScript.RegisterClientScriptBlock

http://book.51cto.com  2009-07-01 09:08  张敏/丁峰译  清华大学出版社  我要评论(0)
  • 摘要:《Visual Basic 2008高级编程(第5版)》第19章使用ASP.NET 3.5,本章介绍许多基础知识,讨论与整个ASP.NET应用程序相关的问题以及建立、部署这些新应用程序的选项。本节为大家介绍使用Page.ClientScript.RegisterClientScriptBlock。

 

19.10.1  使用Page.ClientScript.RegisterClientScriptBlock

RegisterClientScriptBlock方法可以把一个JavaScript函数放在页面的顶部。这说明,该脚本用于启动浏览器中的页面。它的用法如下所示:

  1. <%@ Page Language="VB" %>  
  2.  
  3. <script runat="server">  
  4.     Protected Sub Page_Load(ByVal sender As ObjectByVal e As_  
  5.       System.EventArgs)  
  6.       Dim myScript As String = "function AlertHello() { alert('Hello_  
  7. ASP.NET'); }"  
  8.       Page.ClientScript.RegisterClientScriptBlock(Me.GetType(),_  
  9.          "MyScript",myScript, True)  
  10.     End Sub 
  11. </script>  
  12.  
  13. <html xmlns="http://www.w3.org/1999/xhtml" >  
  14. <head runat="server">  
  15.     <title>Adding JavaScript</title>  
  16. </head>  
  17. <body>  
  18.     <form id="form1" runat="server">  
  19.     <div>  
  20.         <asp:Button ID="Button1" Runat="server" Text="Button" 
  21.          OnClientClick="AlertHello()" />  
  22.     </div>  
  23.     </form>  
  24. </body>  
  25. </html> 

这里把JavaScript函数AlertHello创建为一个字符串myScript。接着使用Page.Client Script.Register ClientScriptBlock方法,将脚本放在页面中。RegisterClientScriptBlock方法的两个结构如下:

RegisterClientScriptBlock(type, key, script)

RegisterClientScriptBlock(type, key, script, script tag specification)

上面的示例指定了类型Me.GetType、键、要包含的脚本,接着是一个设置为True的布尔值,所以.NET会自动用<script>标记把脚本放在ASP.NET页面上。运行该页面时,可以查看页面的源代码,如下所示:

  1. <html xmlns="http://www.w3.org/1999/xhtml" >  
  2. <head><title>  
  3.     Adding JavaScript  
  4. </title></head>  
  5. <body>  
  6.     <form method="post" action="JavaScriptPage.aspx" id="form1">  
  7. <div>  
  8. <input type="hidden" name="__VIEWSTATE" 
  9.  value="/wEPDwUKMTY3NzE5MjIyMGRkiyYSRMg+bcXi9DiawYlbxndiTDo=" />  
  10. </div>  
  11. <script type="text/javascript">  
  12. <!--  
  13. function AlertHello() { alert('Hello ASP.NET'); }// -->  
  14. </script>  
  15.  
  16.     <div>  
  17.         <input type="submit" name="Button1" value="Button" onclick  
  18.           ="AlertHello();" id="Button1" />  
  19.     </div>  
  20.     </form>  
  21. </body>  
  22. </html> 

从这段代码中可以看出,指定的脚本放在ASP.NET页面的页面代码之前。不仅包含<script>标记,还在脚本的外部添加了相应的注释标记(所以旧浏览器不会崩溃)。