Wednesday, November 17, 2010

Register Client Scripts in ASP.NET using ClientScriptManager class

Source: ClientScriptManager Class
C# Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public void Page_Load(Object sender, EventArgs e) {
  // Define the name and type of the client scripts on the page.  
  String csname1 = "PopupScript";
  String csname2 = "ButtonClickScript";
  // Get a ClientScriptManager reference from the Page class.  
  System.Web.UI.ClientScriptManager cs = Page.ClientScript;
  // Check to see if the startup script is already registered.  
  if (!cs.IsStartupScriptRegistered(csname1)) {
   String cstext1 = "alert('Testing');";
   cs.RegisterStartupScript(GetType(), csname1, cstext1, true);
  }
  // Check to see if the client script is already registered.  
  if (!cs.IsClientScriptBlockRegistered(csname2)) {
   StringBuilder cstext2 = new StringBuilder();
   cstext2.Append("");
   cs.RegisterClientScriptBlock(GetType(), csname2, cstext2.ToString(), false);
  }
 }

HTML Markup
1
2
3
4
5
6
<body>  
   <form id="Form1" runat="server">  
   <input type="text" id="Message"/>   
   <input type="button" value="ClickMe" onclick="DoClick()" />  
    </form>  
</body>  

0 comments:

Post a Comment