Click here to Skip to main content
15,886,067 members
Articles / Web Development / ASP.NET
Article

How to Use RegisterClientScriptBlock & RegisterStartupScript

Rate me:
Please Sign up or sign in to vote.
2.58/5 (23 votes)
17 Jun 20042 min read 325.7K   35   5
Example that will populate states in a dropdown menu related to their respective country.

Introduction

One example of using the RegisterClientScriptBlock and RegisterStartupScript demonstrates injecting client side script from an ASP.NET Server Control.

When developing ASP.NET server controls, you should ask yourself how you could enhance the usability through the use of client-side script. Once you have identified these areas, all that remains is to augment the server control so that it emits the proper client-side script.

Now here, I am going to show an example that will populate states in a dropdown menu related to their respective country.

C#
private void Page_Load(object sender, System.EventArgs e)
{
    strConn = 
      System.Configuration.ConfigurationSettings.AppSettings["strConn"];
    sqlConn = new SqlConnection(strConn);
    SqlCommand sqlCommCountry = new 
              SqlCommand("SELECT * FROM CountryMst",sqlConn);
    SqlCommand sqlCommState = new 
              SqlCommand("SELECT * FROM StateMst" + 
              " Order by  CountryCode",sqlConn);
         
    SqlDataAdapter daCountry = new SqlDataAdapter();
    SqlDataAdapter daState = new SqlDataAdapter();
   
    daCountry.SelectCommand = sqlCommCountry;
    daState.SelectCommand = sqlCommState;
    
    DataSet dsUser = new DataSet();
    daCountry.Fill(dsUser,"CountryMst");
    daState.Fill(dsUser,"StateMst");
 
    ddwnPCountry.DataSource=dsUser;
    ddwnPCountry.DataMember="CountryMst";
    ddwnPCountry.DataTextField="CountryName";
    ddwnPCountry.DataValueField="CountryCode";
    ddwnPCountry.DataBind();
    string [] CountryCode = new 
          string[dsUser.Tables["StateMst"].Rows.Count];
    string [] StateName = new 
          string[dsUser.Tables["StateMst"].Rows.Count];
 
    for(int i=0;i<dsUser.Tables["StateMst"].Rows.Count;i++)
    {
        CountryCode[i]=
           dsUser.Tables["StateMst"].Rows[i]["CountryCode"].ToString();
        StateName[i]=
           dsUser.Tables["StateMst"].Rows[i]["StateName"].ToString();
    }
    scriptString+="<script language="JavaScript"> ";
    scriptString+="function setState(ccVal){";
    scriptString+=" document.forms['frmReg']['ddwnPState'].length=0;" + 
                  " cnt=0; for(var i=0;i<arrCountryCode.length;i++)";
    scriptString+="{ if(arrCountryCode[i]==ccVal)" + 
                  " { newOpt=new Option; newOpt.value=arrState[i];" + 
                  " newOpt.text=arrState[i];";
    scriptString+="document.forms['frmReg']['ddwnPState']." + 
                  "options[cnt]=newOpt; cnt=cnt+1; } } } ";
    scriptString+="</script>";
    RegisterStartupScript("arrayScript1", scriptString);
    RegisterArrayDeclaration("arrState"," '" + 
                       String.Join("','",StateName) + "' ");
    RegisterArrayDeclaration("arrCountryCode"," '" + 
                       String.Join("','",CountryCode) + "' ");
  
    ddwnPCountry.Attributes.Add("OnChange","setState(this.value,0)");
}

Description

Now that code, using a DataSet, has generated two arrays of strings: i.e., CountryCode & StateName.

The Join() method is static, requiring the String type identifier, rather than a String instance, to implement the command. The following line from the listing creates a string with all states' elements in sequence, separated by commas.

String.Join("','",StateName) is the function that converts an array of string into a single string separated by commas. Like this:

JavaScript
var arrState =  new Array( 'Albania', 
              'Algeria','American Samoa','Andorra','Angola' ,
              'Anguilla','Antarctica','Antigua and Barbuda',
              'Tierra del Fuego Antartida e Islas del Atlantico Sur',
              'Tucuman','Santiago del Estero','Santa Fe',
              'Santa Cruz','Buenos Aires' )
var arrCountryCode =  new Array( '1','2','3','4','5','6','7',
              '8','9','9','9','9', '9','9','9','9','9',
              '9','9','9','9')

First of all, I am populating data on client side. For this, we have keyword RegisterArrayDeclaration. Through this, the code will generate client side arrays: i.e., arrState & arrCountryCode.

After that, that code generates a JavaScript code that will populate states irrespective to their country into a drop down menu. Code is given below:-

JavaScript
<script language="JavaScript"> 
    Function setState(ccVal)
    {
        document.forms['frmReg']['ddwnPState'].length=0; 
        cnt=0;
        for(var i=0;i<arrCountryCode.length;i++)
        {
            if(arrCountryCode[i]==ccVal)
            {
                newOpt=new Option; newOpt.value=arrState[i];
                newOpt.text=arrState[i];
                document.forms['frmReg']['ddwnPState'].options[cnt]=newOpt;
                cnt=cnt+1;
            }
        }
    }
</script>

The next step is to pass the add client side event on ddwnPCountry that will call setState function on OnChange event. For that, code block in the page load event will add the onchange attribute for the dropdown list as follows:

C#
ddwnPCountry.Attributes.Add("OnChange","setState(this.value,0)");

This code improves the application performance and saves server round trips.

Difference Between RegisterClientScript & RegisterStartupScript

The main difference is that the RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing </form> element. The RegisterClientScriptBlock method places the JavaScript directly after the opening <form> element in the page.

The Base Control

The control that will be used for this article:–

C#
<%@ import Namespace=" System.Web.UI.WebControls.WebControl" %>
<%@ import Namespace="System.Data.SqlClient" %>
<%@ import Namespace="System.Data" %>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
MCSD.NET + MCAD.NET + MCP + OCA

Comments and Discussions

 
GeneralDiff between RegisterStartUpScript and RegisterClientScriptBlock Pin
sanjay3024-Apr-11 3:43
sanjay3024-Apr-11 3:43 
GeneralMy vote of 1 Pin
BigTosha14-Aug-09 3:25
BigTosha14-Aug-09 3:25 
Questionhow to unregister Pin
sherlh225-Aug-06 0:05
sherlh225-Aug-06 0:05 
AnswerRe: how to unregister Pin
nateastle15-Jan-07 10:56
nateastle15-Jan-07 10:56 
AnswerRe: how to unregister Pin
blaze9411-May-07 13:07
blaze9411-May-07 13:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.