Click here to Skip to main content
Click here to Skip to main content

How to Use RegisterClientScriptBlock & RegisterStartupScript

, 17 Jun 2004
Rate this:
Please Sign up or sign in to vote.
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" %>

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

Share

About the Author

SquaredRomi
Web Developer
United States United States
MCSD.NET + MCAD.NET + MCP + OCA

Comments and Discussions

 
GeneralDiff between RegisterStartUpScript and RegisterClientScriptBlock Pinmembersanjay3024-Apr-11 4:43 
GeneralMy vote of 1 PinmemberBigTosha14-Aug-09 4:25 
Questionhow to unregister Pinmembersherlh225-Aug-06 1:05 
AnswerRe: how to unregister Pinmembernateastle15-Jan-07 11:56 
AnswerRe: how to unregister Pinmemberblaze9411-May-07 14:07 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 18 Jun 2004
Article Copyright 2004 by SquaredRomi
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid