Click here to Skip to main content
6,630,586 members and growing! (19,022 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate

How to Use RegisterClientScriptBlock & RegisterStartupScript

By SquaredRomi

Example that will populate states in a dropdown menu related to their respective country.
C#, .NET, WinXP, Win2003, ASP.NET, Visual Studio, Dev
Posted:17 Jun 2004
Views:186,468
Bookmarked:25 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
22 votes for this article.
Popularity: 3.37 Rating: 2.51 out of 5
9 votes, 40.9%
1
2 votes, 9.1%
2
2 votes, 9.1%
3
2 votes, 9.1%
4
7 votes, 31.8%
5

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

About the Author

SquaredRomi


Member
MCSD.NET + MCAD.NET + MCP + OCA
Occupation: Web Developer
Location: United States United States

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralMy vote of 1 PinmemberBigTosha4:25 14 Aug '09  
Generalhow to unregister Pinmembersherlh21:05 25 Aug '06  
GeneralRe: how to unregister Pinmembernateastle11:56 15 Jan '07  
AnswerRe: how to unregister Pinmemberblaze9414:07 11 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Jun 2004
Editor: Smitha Vijayan
Copyright 2004 by SquaredRomi
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project