ASP. NET in the background to register the js script to use the method comparison

  • 2020-06-03 06:16:50
  • OfStack

Page.ClientScript.RegisterClientScriptBlock and Page.ClientScript.RegisterStartupScript:
1. Use Page. ClientScript RegisterClientScriptBlock
c # code
 
<%@ 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 are as follows:
 
<html xmlns= " http://www.w3.org/1999/xhtml "  > 
<head><title> 
Adding JavaScript 
</title></head> 
<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 main difference between RegisterStartupScript and RegisterClientScriptBlock is that RegisterStartupScript places script at the bottom of ES26en.NET page, while RegisterClientScriptBlock places script at the top of ES31en.NET page.
If you have the following code on your page:
 
<asp:TextBox ID= " TextBox1 "  Runat= " server " >Hello ASP.NET</asp:TextBox> 

c#
 
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 ran with an error because JavaScript function was placed in the browser before text box. So JavaScript function cannot find TextBox1.
c#
 
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 JavaScript function at the bottom of ES56en.NET page so that it finds TextBox1 when JavaScript runs.
3. Use Page. ClientScript RegisterClientScriptInclude
Many developers put JavaScript in a.js file and use the RegisterClientScriptInclude method to register JavaScript in a.js file.
c#
 
string myScript =  " myJavaScriptCode.js "  
Page.ClientScript.RegisterClientScriptInclude( " myKey " , myScript); 

This will produce the following structure on the ES76en.NET page:
 
  <script src= " myJavaScriptCode.js "  type= " text/javascript " ></script> 

Related articles: