Populating Cascading DropDownList using jQuery Ajax in ASP.Net

Last Reply one month ago By AnandM

Posted one month ago

Hello there,

I am using jquery for cascading dropdown lists. one for continent and other for corresponding countries.

The continent dropdown is populating but the countries just shows loading and doesnt get populated. I tried with the break point, the list is getting populating, it just the dropdown is not getting activated or shows data. The following is the code i have written:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type = "text/javascript">
    var pageUrl = '<%=ResolveUrl("~/Dropdown.aspx")%>'
    function PopulateContinents() {
        $("#<%=ddlSubcategory.ClientID%>").attr("disabled", "disabled");

        if ($('#<%=ddlCategory.ClientID%>').val() == "0") {
            $('#<%=ddlSubcategory.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');

        }
        else {
            $('#<%=ddlSubcategory.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
            $.ajax({
                type: "POST",
                url: pageUrl + '/PopulateCountries',
                data: '{continentName: ' + $('#<%=ddlCategory.ClientID%> option:selected').html() + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnCountriesPopulated,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }
    }

    function OnCountriesPopulated(response) {
        PopulateControl(response.d, $("#<%=ddlSubcategory.ClientID %>"));
    }
</script>

<script type = "text/javascript">
    function PopulateControl(list, control) {
        if (list.length > 0) {
            control.removeAttr("disabled");
            control.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(list, function () {
                control.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        }
        else {
            control.empty().append('<option selected="selected" value="0">Not available<option>');
        }
    }
</script>


</head>
<body>
    <form id="form1" runat="server">
    <div>
        
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <table>
            <tr>
                <td>Country:</td>
                <td><asp:DropDownList ID="ddlCategory" runat="server" AppendDataBoundItems="true"
             onchange = "PopulateContinents();" >
    <asp:ListItem Text = "Please select" Value = "0"></asp:ListItem>                 
</asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>State:</td>
                <td>
                    <asp:DropDownList ID="ddlSubcategory" runat="server">
    <asp:ListItem Text = "Please select" Value = "0"></asp:ListItem>                 
</asp:DropDownList>
                </td>
            </tr>
            
        </table>
    </ContentTemplate>
</asp:UpdatePanel>

<br /><br />
    </div>
    </form>
</body>
</html>

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Web.DataAccess;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;


public partial class Dropdown : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        this.GetContinentList();
    }

    private void GetContinentList()
    {
        OleDbConnection cn = new OleDbConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["globe"].ConnectionString);
        cn.Open();
        OleDbCommand cmdconti = new OleDbCommand("select * from ContinentTable order by ContiName", cn);
        cmdconti.CommandType = CommandType.Text;
        OleDbDataAdapter da = new OleDbDataAdapter(cmdconti);
        DataSet ds = new DataSet();
        da.Fill(ds);


        ddlCategory.DataSource = ds;
        ddlCategory.DataTextField = "ContiName";
        ddlCategory.DataValueField = "ContiName";
        ddlCategory.DataBind();

        cn.Close();
    }


    [System.Web.Services.WebMethod]
    public static ArrayList PopulateCountries(string continentName)
    {
        ArrayList list = new ArrayList();
        String strConnString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["globe"].ConnectionString;
        String strQuery = "select countryID, countryName from CountryTable where continentName=@continentName order by countryName";
        using (OleDbConnection con = new OleDbConnection(strConnString))
        {
            using (OleDbCommand cmd = new OleDbCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@continentName", continentName);
                cmd.CommandText = strQuery;
                cmd.Connection = con;
                con.Open();
                OleDbDataReader sdr = cmd.ExecuteReader();
                while (sdr.Read())
                {
                    list.Add(new ListItem(
                   sdr["countryName"].ToString(),
                   sdr["countryID"].ToString()
                    ));
                }
                con.Close();
                return list;
            }
        }
    }



    private void PopulateDropDownList(ArrayList list, DropDownList ddl)
    {
        ddl.DataSource = list;
        ddl.DataTextField = "Text";
        ddl.DataValueField = "Value";
        ddl.DataBind();
    }


}

I dont know if i am missing anything...

Hope someone can help me out.

Posted one month ago Modified on one month ago

Hi jain4,

I have created a sample with your code and its working fine at my side refer below sample code and modify the code according to your need.

The Database table structure is same as used in below article

AJAX Cascading DropDownList using jQuery in ASP.Net

HTML

<div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <table>
                <tr>
                    <td>
                        Continent :
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlCategory" runat="server" AppendDataBoundItems="true" onchange="PopulateContinents();">
                            <asp:ListItem Text="Please select" Value="0"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        Country:
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlSubcategory" runat="server">
                            <asp:ListItem Text="Please select" Value="0"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>
<div>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        var pageUrl = '<%=ResolveUrl("~/Default.aspx")%>'
        function PopulateContinents() {
            $("#<%=ddlSubcategory.ClientID%>").attr("disabled", "disabled");

            if ($('#<%=ddlCategory.ClientID%>').val() == "0") {
                $('#<%=ddlSubcategory.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');

            }
            else {
                $('#<%=ddlSubcategory.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
                $.ajax({
                    type: "POST",
                    url: pageUrl + '/PopulateCountries',
                    data: '{continentName: "' + $('[id*=ddlCategory] option:selected').html() + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnCountriesPopulated,
                    failure: function (response) {
                        alert(response.d);
                    }
                });
            }
        }

        function OnCountriesPopulated(response) {
            PopulateControl(response.d, $("#<%=ddlSubcategory.ClientID %>"));
        }
    </script>
    <script type="text/javascript">
        function PopulateControl(list, control) {
            if (list.length > 0) {
                control.removeAttr("disabled");
                control.empty().append('<option selected="selected" value="0">Please select</option>');
                $.each(list, function () {
                    control.append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
            else {
                control.empty().append('<option selected="selected" value="0">Not available<option>');
            }
        }
    </script>
</div>

C#

protected void Page_Load(object sender, EventArgs e)
{
    this.GetContinentList();
}

private void GetContinentList()
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string query = "SELECT [ID],[ContinentName] FROM [Continents];";

        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        ddlCategory.DataSource = ds.Tables[0];
                        ddlCategory.DataTextField = "ContinentName";
                        ddlCategory.DataValueField = "ContinentName";
                        ddlCategory.DataBind();
                    }
                }
            }
        }
    }
    //OleDbConnection cn = new OleDbConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["globe"].ConnectionString);
    //cn.Open();
    //OleDbCommand cmdconti = new OleDbCommand("select * from ContinentTable order by ContiName", cn);
    //cmdconti.CommandType = CommandType.Text;
    //OleDbDataAdapter da = new OleDbDataAdapter(cmdconti);
    //DataSet ds = new DataSet();
    //da.Fill(ds);


    //ddlCategory.DataSource = ds;
    //ddlCategory.DataTextField = "ContiName";
    //ddlCategory.DataValueField = "ContiName";
    //ddlCategory.DataBind();

    //cn.Close();
}

[System.Web.Services.WebMethod]
public static ArrayList PopulateCountries(string continentName)
{
    ArrayList list = new ArrayList();
    //String strConnString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["globe"].ConnectionString;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    String strQuery = "SELECT [ID],[ContinentID],[CountryName] FROM [Countries] WHERE [ContinentID] = (SELECT [ID] FROM [Continents] WHERE [ContinentName] = @ContinentName) ORDER BY CountryName";

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(strQuery, con))
        {
            con.Open();
            cmd.Parameters.AddWithValue("@ContinentName", continentName);
            SqlDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                list.Add(new ListItem(
                sdr["CountryName"].ToString(),
                sdr["ID"].ToString()
                ));
            }
            con.Close();
            return list;
        }
    }
    //using (OleDbConnection con = new OleDbConnection(strConnString))
    //{
    //    using (OleDbCommand cmd = new OleDbCommand())
    //    {
    //        cmd.CommandType = CommandType.Text;
    //        cmd.Parameters.AddWithValue("@continentName", continentName);
    //        cmd.CommandText = strQuery;
    //        cmd.Connection = con;
    //        con.Open();
    //        OleDbDataReader sdr = cmd.ExecuteReader();
    //        while (sdr.Read())
    //        {
    //            list.Add(new ListItem(
    //           sdr["countryName"].ToString(),
    //           sdr["countryID"].ToString()
    //            ));
    //        }
    //        con.Close();
    //        return list;
    //    }
    //}
}

private void PopulateDropDownList(ArrayList list, DropDownList ddl)
{
    ddl.DataSource = list;
    ddl.DataTextField = "Text";
    ddl.DataValueField = "Value";
    ddl.DataBind();
}

VB.Net

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    Me.GetContinentList()
End Sub

Private Sub GetContinentList()
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "SELECT [ID],[ContinentName] FROM [Continents];"

        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand(query)
                Using sda As New SqlDataAdapter()
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Using ds As New DataSet()
                        sda.Fill(ds)
                        ddlCategory.DataSource = ds.Tables(0)
                        ddlCategory.DataTextField = "ContinentName"
                        ddlCategory.DataValueField = "ContinentName"
                        ddlCategory.DataBind()
                    End Using
                End Using
            End Using
        End Using
    End If
    'OleDbConnection cn = new OleDbConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["globe"].ConnectionString);
    'cn.Open();
    'OleDbCommand cmdconti = new OleDbCommand("select * from ContinentTable order by ContiName", cn);
    'cmdconti.CommandType = CommandType.Text;
    'OleDbDataAdapter da = new OleDbDataAdapter(cmdconti);
    'DataSet ds = new DataSet();
    'da.Fill(ds);


    'ddlCategory.DataSource = ds;
    'ddlCategory.DataTextField = "ContiName";
    'ddlCategory.DataValueField = "ContiName";
    'ddlCategory.DataBind();

    'cn.Close();
End Sub

<System.Web.Services.WebMethod()> _
Public Shared Function PopulateCountries(continentName As String) As ArrayList
    Dim list As New ArrayList()
    'String strConnString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["globe"].ConnectionString;
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim strQuery As [String] = "SELECT [ID],[ContinentID],[CountryName] FROM [Countries] WHERE [ContinentID] = (SELECT [ID] FROM [Continents] WHERE [ContinentName] = @ContinentName) ORDER BY CountryName"

    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(strQuery, con)
            con.Open()
            cmd.Parameters.AddWithValue("@ContinentName", continentName)
            Dim sdr As SqlDataReader = cmd.ExecuteReader()
            While sdr.Read()
                list.Add(New ListItem(sdr("CountryName").ToString(), sdr("ID").ToString()))
            End While
            con.Close()
            Return list
        End Using
    End Using
    'using (OleDbConnection con = new OleDbConnection(strConnString))
    '{
    '    using (OleDbCommand cmd = new OleDbCommand())
    '    {
    '        cmd.CommandType = CommandType.Text;
    '        cmd.Parameters.AddWithValue("@continentName", continentName);
    '        cmd.CommandText = strQuery;
    '        cmd.Connection = con;
    '        con.Open();
    '        OleDbDataReader sdr = cmd.ExecuteReader();
    '        while (sdr.Read())
    '        {
    '            list.Add(new ListItem(
    '           sdr["countryName"].ToString(),
    '           sdr["countryID"].ToString()
    '            ));
    '        }
    '        con.Close();
    '        return list;
    '    }
    '}
End Function

Private Sub PopulateDropDownList(list As ArrayList, ddl As DropDownList)
    ddl.DataSource = list
    ddl.DataTextField = "Text"
    ddl.DataValueField = "Value"
    ddl.DataBind()
End Sub

ScreenShot

 

 

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html?aff_id=108