Skip to content
Amal Hashim
All posts
Article

ASP.Net JQuery Cascading Dropdown

Build a cascading dropdown in ASP.NET with jQuery and a page method: pick an author and the books drop down fills in.

2 min read#ASP.NET#C##jQuery

A cascading dropdown fills one list based on the selection in another. This example uses a parent and child relationship of authors and books. When an author is selected, that author's books are loaded into the second drop down.

jQuery calls a static [WebMethod] on the page, so the page does not post back.

Code behind

csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            //Assume this list we get from database
            List<string> authors = new List<string>()
            {
                "Stephen King",
                "Nicholas Sparks",
                "Jodi Picoult",
                "Nora Roberts"
            };

            this.ddlAuthors.DataSource = authors;
            this.ddlAuthors.DataBind();
        }
    }

    [WebMethod()]
    public static string GetBooks(string author)
    {
        //Author = Key and Book = Value
        Dictionary<string, List<string>> books =
            new Dictionary<string, List<string>>()
        {
            {"Stephen King", new List<string>()
                {"The Stand", "It", "The Shining"} },
            {"Nicholas Sparks", new List<string>()
                {"The Notebook", "The Last Song", "A Walk to Remember", "Dear John"} },
            {"Jodi Picoult", new List<string>()
                {"My Sister's Keeper", "Nineteen Minutes", "The Pact", "Plain Truth"} },
            {"Nora Roberts", new List<string>()
                {"Montana Sky", "Angels Fall", "Carolina Moon", "Northern Lights"} }
        };

        if (books.ContainsKey(author))
        {
            return string.Join(";", books[author].ToArray());
        }

        return string.Empty;
    }
}

Aspx page

html
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<!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 type="text/javascript"
    src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#' + '<%=this.ddlAuthors.ClientID %>').change(FillBooks);
        });

        function FillBooks() {
            $.ajax(
                {
                    type: "POST",
                    url: "Default.aspx/GetBooks",
                    data: "{'author':'" +
                        $('#' + '<%=this.ddlAuthors.ClientID %>').val() + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: successFillBooks,
                    error: errorFillBooks
                }
            );
        }
        function successFillBooks(result) {
            if (result["d"] != null) {
                var books = result["d"].split(';');
                var length = books.length;
                var dropDown = document.getElementById('<%=ddlBooks.ClientID %>');
                dropDown.options.length = 0;
                for (var i = 0; i < length; ++i) {
                    var option = document.createElement("option");
                    option.text = books[i];
                    option.value = books[i];
                    dropDown.options.add(option);
                }
            }
        }
        function errorFillBooks() {
            alert("Error occurred");
        }
    </script>
    <form id="form1" runat="server">
    <div>
        Authors: <asp:DropDownList ID="ddlAuthors" runat="server">
</asp:DropDownList>
        <br />
        Books: <asp:DropDownList ID="ddlBooks" runat="server">
</asp:DropDownList>
    </div>
    </form>
</body>
</html>

Example

  1. Open the page. The Authors list shows the four authors.
  2. Select "Stephen King".
  3. jQuery posts {'author':'Stephen King'} to Default.aspx/GetBooks.
  4. The method returns The Stand;It;The Shining and the script fills the Books list from that string.