[Sample of Mar 6th] ASP.NET cascading drop-down-list

 

Homepage image
Sample of the Day RSS Feed

Sample download
C# version: https://code.msdn.microsoft.com/CSASPNETCascadingDropDownLi-0a3f1ecf
VB version: https://code.msdn.microsoft.com/VBASPNETCascadingDropDownLi-baabc3b7 

imageToday’s code sample demonstrates how to create a cascading DropDownList in ASP.NET in two ways.  One with postback, and the other with callback.  The former solution will save the selected option value in hidden text, and restore them when page is postback.  The latter solution creates a XmlHttpRequest object and sends callback to .aspx page when dropdownlist control options is changed.

The sample was written by the sample writer: Arwind Gao.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage https://1code.codeplex.com/.

 

Introduction

The example shows how to create Cascading DropDownList in two ways. You can view the Default.aspx page, and then you can find there're two links in this page:

  • Use ASP.NET DropDownList control with postback.
  • Use ASP.NET DropDownList control with callback.

The CascadingDropDownListWithPostBack.aspx will save the selected option value in hidden text, and restore them when page is postback, the CascadingDropDownListWithCallBack.aspx page will create a XmlHttpRequest object and send callback to .aspx page when dropdownlist control options is changed.

 

Running the Sample

Please follow these demonstration steps below.

Step 1: Open the CSASPNETCascadingDropDownList.sln. Expand the CSASPNETCascadingDropDownList web application and press Ctrl + F5 to show the default.aspx.

Step 2: We will see two links on default.aspx page, the two links point to CascadingDropDownListWithPostBack.aspx page and CascadingDropDownListWithCallBack.aspx page respectively. You can click one of them, and you may find these two web form pages appear to be similar to each other, but actually they achieve the same goal with different methods.

image

Step 3: There are three cascading dropdownlist controls and one button on the target page, please try to select the options which you like, and click submit button.

image

Step 4:  The page will give the summary information for your selected options, just like the following screenshot.

Step 5: Now please click the “Go Back to Default page” link, you can test the CascadingDropDownListWithCallBack.aspx page now\

Step 6: Validation finished.

 

Using the Code

Step 1. Create a C# "ASP.NET Empty Web Application" in Visual Studio 2010. Name it as "CSASPNETCascadingDropDownList". Add four web form pages in the root directory of the application, Default.aspx page is used to show different cascading dropdownlist pages, the CascadingDropDownListWithCallBack.aspx page is used to show the cascading dropdownlist with callback method, the CascadingDropDownListWithPostBack.aspx page is used to show the cascading dropdownlist with postback method, the GetDataForCallBack.aspx page is used to retrieve data in callback and write data to client-side application.

Step 2. The CascadingDropDownListWithCallBack.aspx page will use JavaScript functions to create XmlHttpRequest object for saving and restoring data, and we should add onChange event in Dropdownlist control for call ddlCountryOnChange() function.

The following code snippet is from Jscript.js file:

 var xmlHttp = null; // XMLHttpRequest object 
var ddlCountry = null; // DropDownList for country 
var ddlRegion = null; // DropDownList for region 
var ddlCity = null;  // DropDownList for city 
var hdfRegion = null; // Use to save region DropDownList options and restore it when page is rendering 
var hdfCity = null;  // Use to save city DropDownList options and restore it when page is loadrenderinged 
var hdfRegionSelectValue = null; // Use to save region DropDownList selected options and restore it when page is rendering 
var hdfCitySelectValue = null; // Use to save city DropDownList selected options and restore it when page is rendering 
var hdfCountrySelectValue = null;   // Use to save country DropDownList selected options and restore it when page is rendering 
 
 
// Instance XMLHttpRequest 
window.onload = function loadXMLHttp() { 
    if (window.XMLHttpRequest) { 
        xmlHttp = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
        try { 
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
        catch (e) { } 
    } 
 
 
    ddlCountry = document.getElementById('ddlCountry'); 
    ddlRegion = document.getElementById('ddlRegion'); 
    ddlCity = document.getElementById('ddlCity'); 
    hdfRegion = document.getElementById('hdfRegion'); 
    hdfCity = document.getElementById('hdfCity'); 
    hdfRegionSelectValue = document.getElementById('hdfRegionSelectValue'); 
    hdfCitySelectValue = document.getElementById('hdfCitySelectValue'); 
    hdfCountrySelectValue = document.getElementById('hdfCountrySelectValue'); 
    ShowFirstOption(ddlCountry); // Add "Please Select a xxxx" option in the top of country DropDownList  
    RestoreDropdownlist(); // Restore dropdownlist when page is rendering 
 
 
} 
 
 
// Restore dropdownlist when page is rendering 
function RestoreDropdownlist() { 
    // Restore region dropdownlist 
    if (hdfRegion.value != "") { 
        addOption(ddlRegion, hdfRegion.value); 
        ddlRegion.selectedIndex = hdfRegionSelectValue.value; 
    } // Restore city dropdownlist 
    if (hdfCity.value != "") { 
        addOption(ddlCity, hdfCity.value); 
        ddlCity.selectedIndex = hdfCitySelectValue.value; 
    } 
    ddlCountry.selectedIndex = hdfCountrySelectValue.value; 
} 
 
 
// Save selected options in hide field so that we can access it from codebehind class 
function SaveSelectedData() { 
 
 
    hdfCitySelectValue.value = ddlCity.selectedIndex; 
    hdfCountrySelectValue.value = ddlCountry.selectedIndex; 
    hdfRegionSelectValue.value = ddlRegion.selectedIndex; 
 
 
    if (ddlCity != null && ddlCountry != null && ddlRegion != null 
     && ddlCity.length > 0 && ddlCountry.length > 0 && ddlRegion.length > 0 
     && ddlCity.selectedIndex != '0' && ddlCountry.selectedIndex != '0' && ddlRegion.selectedIndex != '0') { 
 
 
        var strResult = ddlCountry.options[ddlCountry.selectedIndex].value + '; ' 
        + ddlRegion.options[ddlRegion.selectedIndex].value + '; ' 
        + ddlCity.options[ddlCity.selectedIndex].value; 
 
 
        document.getElementById('hdfResult').value = strResult; 
    } 
    else { 
        document.getElementById('hdfResult').value = 'Please select option from DropDownList.'; 
    } 
} 

Then you can handle data binding event in code-behind file.  The following code is used to bind data with dropdownlist controls and handle on submit button.

 /// <summary> 
/// Page Load event 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
protected void Page_Load(object sender, EventArgs e) 
{ 
    // Register client onclick event for submit button 
    btnSubmit.Attributes.Add("onclick", "SaveSelectedData();"); 
    if (!IsPostBack) 
    { 
        // Bind country dropdownlist 
        BindddlCountry(); 
        // Initialize hide field value 
        hdfResult.Value = ""; 
        hdfCity.Value = ""; 
        hdfCitySelectValue.Value = "0"; 
        hdfRegion.Value = ""; 
        hdfRegionSelectValue.Value = ""; 
    } 
} 
 
 
 
 
/// <summary> 
/// Bind country dropdownlist 
/// </summary> 
public void BindddlCountry() 
{ 
    List<string> list = RetrieveDataFromXml.GetAllCountry(); 
    ddlCountry.DataSource = list; 
    ddlCountry.DataBind(); 
} 
 
 
 
 
/// <summary> 
/// Submit button click event and show select result 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
protected void btnSubmit_Click(object sender, EventArgs e) 
{ 
    // Get result from hide field saved in client 
    string strResult = hdfResult.Value; 
    lblResult.Text = strResult; 
} 

Step 3. Then you need to use GetDataForCallback.aspx page to retrieve data and write data to the client.

The following code is used to retrieve and write data by callback method.

 /// <summary> 
/// Get region based on country value 
/// </summary> 
/// <param name="strValue">The country value</param> 
public void RetrieveRegionByCountry(string strValue) 
{ 
    List<string> list = RetrieveDataFromXml.GetRegionByCountry(strValue); 
    WriteData(list); 
} 
 
 
/// <summary> 
/// Get city based on region value 
/// </summary> 
/// <param name="strValue">The region value</param> 
public void RetrieveCityByRegion(string strValue) 
{ 
    List<string> list = RetrieveDataFromXml.GetCityByRegion(strValue); 
    WriteData(list); 
} 
 
 
/// <summary> 
/// Write data to client 
/// </summary> 
/// <param name="list">The list contains value </param> 
public void WriteData(List<string> list) 
{ 
    int iCount = list.Count; 
    StringBuilder builder = new StringBuilder(); 
    if (iCount > 0) 
    { 
        for (int i = 0; i < iCount - 1; i++) 
        { 
            builder.Append(list[i] + ","); 
        } 
        builder.Append(list[iCount - 1]); 
    } 
 
 
    Response.ContentType = "text/xml"; 
    // Write data in string format "###,###,###" to client 
    Response.Write(builder.ToString()); 
    Response.End(); 
} 

Step 4. The next step, we need to implement cascading dropdownlist control, we must implement Dropdownlist’s SelectedIndexChanged event. Here we also need to add JavaScript functions to bind data with those controls.

The following code is showing how to implement with DropDownList SelectedIndexChanged event.

 /// <summary> 
/// Country dropdownlist SelectedIndexChanged event 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    // Remove region dropdownlist items 
    ddlRegion.Items.Clear(); 
    string strCountry = string.Empty; 
    strCountry = ddlCountry.SelectedValue; 
    List<string> list = null; 
 
 
    // Bind Region dropdownlist based on country value 
    if (ddlCountry.SelectedIndex != 0) 
    { 
        list = RetrieveDataFromXml.GetRegionByCountry(strCountry); 
        if (list != null && list.Count != 0) 
        { 
            ddlRegion.Enabled = true; 
        } 
 
 
        ddlRegion.DataSource = list; 
        ddlRegion.DataBind(); 
    } 
    else 
    { 
        ddlRegion.Enabled = false; 
    } 
 
 
    ddlRegion.Items.Insert(0, new ListItem("Select Region", "-1")); 
 
 
    // Clear city dropdownlist 
    ddlCity.Enabled = false; 
    ddlCity.Items.Clear(); 
    ddlCity.Items.Insert(0, new ListItem("Select City", "-1")); 
 
 
    // Initialize city dropdownlist selected index 
    hdfDdlCitySelectIndex.Value = "0"; 
} 
 
 
 
 
/// <summary> 
/// Region dropdownlist SelectedIndexChanged event 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    // Bind city dropdownlist based on region value 
    string strRegion = string.Empty; 
    strRegion = ddlRegion.SelectedValue; 
    List<string> list = null; 
    list = RetrieveDataFromXml.GetCityByRegion(strRegion); 
    ddlCity.Items.Clear(); 
    ddlCity.DataSource = list; 
    ddlCity.DataBind(); 
    ddlCity.Items.Insert(0, new ListItem("Select City", "-1")); 
 
 
    // Initialize city dropdownlist selected index 
    hdfDdlCitySelectIndex.Value = "0"; 
 
 
    // Enable city dropdownlist when it has items 
    if (list.Count > 0) 
    { 
        ddlCity.Enabled = true; 
    } 
    else 
    { 
        ddlCity.Enabled = false; 
    } 
} 

 

More Information

ASP.NET DropDownList Control

XMLHttpRequest Object

XmlDocument Class