65.9K
CodeProject is changing. Read more.
Home

How to Use RegisterClientScriptBlock & RegisterStartupScript

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.58/5 (23 votes)

Jun 18, 2004

2 min read

viewsIcon

326553

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.

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:

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:-

<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:

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:–

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