With Page.ClientScript.RegisterClientScriptBlock and Page.ClientScript.RegisterStartupScript: difference:
1. Use of Page.ClientScript.RegisterClientScriptBlock
C # code
Copy Code code as follows:
<%@ Page language= "C #"%>
<script runat= "Server" >
protected void Page_Load (object sender, EventArgs e)
{
String myScript = @ "function Alerthello () {alert (' Hello ASP. NET '); }”;
Page.ClientScript.RegisterClientScriptBlock (this. GetType (),
"MyScript", MyScript, True);
}
</script>
The results of the operation are as follows:
Copy Code code as follows:
Adding JavaScript
</title><body>
<form method= "POST" action= "javascriptpage.aspx" id= "Form1" >
<div>
<input type= "hidden" name= "__viewstate"
Value= "/wepdwukmty3nze5mjiymgrkiyysrmg+bcxi9diawylbxnditdo="/>
</div>
<script type= "Text/javascript" >
<!--
function Alerthello () {alert (' Hello ASP '). NET '); }//-->
</script>
<div>
<input type= "Submit" Name= "Button1" value= "button" onclick= "Alerthello ();"
Id= "Button1"/>
</div>
</form>
</body>
2. Use of Page.ClientScript.RegisterStartupScript
The biggest difference between the RegisterStartupScript method and the RegisterClientScriptBlock method is that RegisterStartupScript places the script at the bottom of the ASP.net page, and registerclientscriptblock the script at the top of the ASP.net page.
If you have the following code in your page:
Copy Code code as follows:
<asp:textbox id= "TextBox1" runat= "Server" >hello asp.net</asp:textbox>
C#
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
String myScript = @ "alert (document.forms[0][' TextBox1 '].value);";
Page.ClientScript.RegisterClientScriptBlock (this. GetType (), "MyScript", MyScript, True);
}
This page runs with an error, because the JavaScript function is placed in the browser before text box. Therefore, the JavaScript function cannot find TextBox1.
C#
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
String myScript = @ "alert (document.forms[0][' TextBox1 '].value);";
Page.ClientScript.RegisterStartupScript (this. GetType (), "MyScript", MyScript, True);
}
This code places the JavaScript function at the bottom of the ASP.net page, so it can find TextBox1 when JavaScript is running.
3. Use of Page.ClientScript.RegisterClientScriptInclude
Many developers place JavaScript in the. js file, using the RegisterClientScriptInclude method to register JavaScript in the. js file.
C#
Copy Code code as follows:
String myScript = "Myjavascriptcode.js"
Page.ClientScript.RegisterClientScriptInclude ("MyKey", myScript);
This will produce the following structure on the ASP.net page:
Copy Code code as follows:
<script src= "Myjavascriptcode.js" type= "Text/javascript" ></script>