Custom Search Tailored for Microsoft .NET  
Aspexception.com Skip Navigation Links
Error RepositoryExpand Error Repository
.NET ResourcesExpand .NET Resources
About
Skip Navigation LinksHome > .NET Resources > How to tips... > Register Client Script
How to programmatically generate javascript code in ASP.NET page
To dynamically generate the javascript code in ASP.NET page, developers can use ClientScriptManager.RegisterStartupScript or ClientScriptManager.RegisterClientScriptBlock.
The following example shows how to register startup javascript code and callback javascript code for a button.
<%@ Page Language="C#"%>
<script runat="server">
  public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client scripts on the page.
    String strClientScriptName1 = "PopupScript";
    String strClientScriptName2 = "ButtonClickScript";
    Type cstype = this.GetType();
        
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, strClientScriptName1))
    {
      String cstext1 = "alert('Hello World');";
      cs.RegisterStartupScript(cstype, strClientScriptName1, cstext1, true);
    }

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(cstype, strClientScriptName2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=text/javascript> function DoClick() {");
      cstext2.Append("Form1.Message.value=Form1.TextBox1.value} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, strClientScriptName2, cstext2.ToString(), false);
    }
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ClientScriptManager Example</title>
  </head>
  <body>
     <form id="Form1"
         runat="server">
        <input type="text" id="Message" /> <input type="button" value="ClickMe" onclick="DoClick()" />
        <asp:textbox id="TextBox1" runat="server" text="Sample Text" />

     </form>
  </body>
</html>
Site Map  Copyright © Aspexception.com 2008. All rights Reserved. Terms of Use