C#後臺添加js腳本

一、使用Response.Write
1.方法:
Response.Write("<script languge='javascript'>alert('成功改動');</script>");
2.常見問題:
(1)問題:Response.Write 後連接Response.Redirect ,則Response.Write無法顯示,直接跳轉入Response.Redirect 的頁面。
解決方法:跳轉頁面寫在js中,如
Response.Write("<script languge='javascript'>alert('成功改動');window.location.href='index.aspx'</script>");
(2)問題:假設在Ajax的UpdatePanel中的button中用Response.Redirect()或Response.Write()進行URL帶參數的頁面重定向時出現錯誤。
因爲Ajax是無刷新的,而使用Response進行帶參重定向時須要刷新頁面。
解決方法:在UpdatePanel下設置“asp: PostBackTrigger”的“ControlID”爲指定的控件名稱即可,如:
<Triggers>
<asp:PostBackTrigger ControlID="GridView" />
</Triggers>
能夠用註冊client事件的方法解決UpdatePanel中的重定向問題
跳轉到某一指定頁面Response.Redirect("xxx.aspx?yy="+Ftype+"");  
Response.Write("<script languge='javascript'>window.parent.popupContent.Hide();</script>");
Response.Write("<script languge='javascript'>window.parent.grdCarToOther.PerformCallback(" + iCrdID + ");</script>");

二、使用RegisterClientScriptBlock
1.方法
public void RegisterClientScriptBlock(Type type, string key, string script)
public void RegisterClientScriptBlock(Type type, string key, string script, bool addScriptTags)
eg:ClientScript.RegisterClientScriptBlock(this.GetType(), "script1", "alert(1);", true);
2.參數介紹: 
(1)type 要註冊的啓動腳本的類型。
(2)key 要註冊的啓動腳本的鍵,也就是你自己給這段腳本起的名字。相同 key 的腳本被當作是重複的,對於這樣的腳本只輸出最先註冊的,
(3)ClientScriptBlock 和 StartupScript 中的 key 相同不算是重複的。script 腳本代碼。
(4)addScriptTags 是否添加 <script> 標籤,如果腳本代碼中不含 <script> 標籤,則應該指定該值爲 true,若不指定該值,會被當作 false 對待。
RegisterClientScriptBlock 與 RegisterStartupScript 的區別:
ClientScript.RegisterClientScriptBlock(this.GetType(), "script1", "alert(1);", true);
ClientScript.RegisterStartupScript(this.GetType(), "script1", "alert(2);", true);

三、使用RegisterStartupScript
1.方法:
public void RegisterStartupScript(Type type, string key, string script)
public void RegisterStartupScript(Type type, string key, string script, bool addScriptTags)
eg:ClientScript.RegisterStartupScript(this.GetType(), "script2", "alert(4);", true);
2.參數介紹:
同RegisterClientScriptBlock的參數介紹。

四、三者區別:
1.Response.Write可以輸出JavaScript,但輸出的內容是在 <html> 之前,這會導致一些問題,比如樣式表失效,甚至會導致一些脆弱的瀏覽器發生錯誤。
2.ClientScript則可以方便地管理 JavaScript,應該說 ClientScript.RegisterClientScriptBlock 與 ClientScript.RegisterStartupScript只有一點區別,那就是RegisterClientScriptBlock將腳本代碼寫在 <form> 之後,而 RegisterStartupScript 將代碼寫在 </form>(注意是結束標籤)之前。
發佈了124 篇原創文章 · 獲贊 20 · 訪問量 52萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章