1. 程式人生 > >【.Net碼農】.NET中執行js指令碼的方法

【.Net碼農】.NET中執行js指令碼的方法

一、後臺註冊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方法 
前臺程式碼:

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

後臺程式碼:

  1. publicstring str = "黎明";  
  2.     protectedvoid Page_Load(object sender, EventArgs e)  
  3.     {  
  4.         Page.DataBind(); //只有執行了此方法,前臺繫結才會生效
  5.     }