Use Page. ClientScript. RegisterClientScriptBlock and Page. ClientScript. RegisterStartupScript: difference:
1. Use Page. ClientScript. RegisterClientScriptBlock
C # code
Copy codeThe Code is 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 running result is as follows:
Copy codeThe Code is as follows:
<Html xmlns = "http://www.w3.org/5o/xhtml">
<Head> <title>
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>
</Html>
2. Use Page. ClientScript. RegisterStartupScript
The biggest difference between the RegisterStartupScript method and the RegisterClientScriptBlock method is that RegisterStartupScript places the script at the bottom of ASP. NET page, while RegisterClientScriptBlock places the script at the top of ASP. NET page.
If your page contains the following code:
Copy codeThe Code is as follows:
<Asp: TextBox ID = "TextBox1" Runat = "server"> Hello ASP. NET </asp: TextBox>
C #
Copy codeThe Code is 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 );
}
When the page is running, an error is reported because the JavaScript function is placed in the browser before the text box. Therefore, TextBox1 cannot be found for JavaScript Functions.
C #
Copy codeThe Code is 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 ASP. NET page. Therefore, TextBox1 can be found during JavaScript execution.
3. Use Page. ClientScript. RegisterClientScriptInclude
Many developers place JavaScript in. js files and use the RegisterClientScriptInclude method to register JavaScript in. js files.
C #
Copy codeThe Code is as follows:
String myScript = "myJavaScriptCode. js"
Page. ClientScript. RegisterClientScriptInclude ("myKey", myScript );
This will generate the following structure on the ASP. NET page:
Copy codeThe Code is as follows:
<Script src = "myJavaScriptCode. js" type = "text/javascript"> </script>