【.Net码农】 .NET中执行js脚本的方法

来源:互联网 发布:计算器vb程序代码 编辑:程序博客网 时间:2024/04/28 15:10

http://blog.csdn.net/zouyujie1127/article/details/7192961



一、后台注册js脚本

在项目开发中,遇到了问题,当使用了UpdatePanel控件后,直接在后台输出js脚本报错了。

大家都知道向客户端输出内容的方式很多,而大多数初学者会使用Respone.Write(string)。比如:

以下是代码片段:
Respone.Write(“hello word!”); 
  或输出JS 
  Respone.Write("");

  但是,当你查看客户端源码时,你会发现,输出的内容呈现在源码的最前端,显然它破坏了HTML的格式,在某些情况下这是会影响到页面布局等效果的。

  正确的输出方式应该是:this.ClientScript.RegisterStartupScript或this.ClientScript.RegisterClientScriptBlock.

  this.ClientScript.RegisterStartupScript 是在Form开始的第一行注册脚本,后者则是在Form结尾处注册脚本。这样就不回破坏HTML得格式了,如:

以下是代码片段:
this.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey", "") 
  或 
  this.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey", "alert('hello word!');",True)
  this.ClientScript.RegisterClientScriptBlock也类似。 
  UpdatePanel

  当你想在UpdatePanel内输出一段JS时,运用以上方法就会得不到预期的效果。那么请看一下示例。

  有一个UpdatePanel的ID是upPn

以下是代码片段:
ScriptManager.RegisterClientScriptBlock(upPn,this.GetType(), "scriptKey", "alert('hello word!');",True)
  或 
  ScriptManager.RegisterStartupScript(upPn,this.GetType(), "scriptKey", "alert('hello word!');",True)

  这样的话,当UpdatePanel内容加载到客户端后,就会弹出“hello word!”对话框。

  这样的话,从后台输出JS就更加方便了。

二、前台直接绑定js方法 
前台代码:

[html] view plaincopy
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4.     <script type="text/javascript">  
  5.         function ShowInfo(msg) {  
  6.             alert(msg + ',Hello');  
  7.         }  
  8.     </script>  
  9. </head>  
  10. <body>  
  11.     <form id="form1" runat="server">  
  12.     <div>  
  13.     <a href="#" onclick='<%#string.Format("ShowInfo(\"{0}\");",str) %>'>显示</a>  
  14.     </div>  
  15.     </form>  
  16. </body>  
  17. </html>  

后台代码:

[csharp] view plaincopy
  1. public string str = "黎明";  
  2.     protected void Page_Load(object sender, EventArgs e)  
  3.     {  
  4.         Page.DataBind(); //只有执行了此方法,前台绑定才会生效  
  5.     }  

版权声明:本文为博主原创文章,未经博主允许不得转载。


0 0
原创粉丝点击