Home > ASP.Net, C#, jQuery > ASP.Net JQuery Cascading Dropdown

ASP.Net JQuery Cascading Dropdown

In this article I am going to explain how easily we can implement cascading drop down in an asp.net web application. To illustrate assume we have parent child relationship Authors and Books. Once Author is selected the Books of that Author should get populated on the second drop down control.

CodeBehind

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", "Ninteen Minutes", "The Pact", "Plain Truth"} },
           {"Nora Roberts", new List<string>() 
{"Montana Sky", "Angels Fall", "Carolina Moon", "Northern Ligths"} }
        };

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

        return string.Empty;
    }
}

Aspx Page

<%@ 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;
                document.getElementById('<%=ddlBooks.ClientID %>').
options.length = 0;
                var dropDown = document.
getElementById('<%=ddlBooks.ClientID %>');
                for (var i = 0; i < length - 1; ++i) {
                    var option = document.createElement("option");
                    option.text = books[i];
                    option.value = books[i];
                    dropDown.options.add(option);
                }
            }
        }
        function errorFillBooks() {
            alert("Error occured");
        }
    </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>

Advertisements
Categories: ASP.Net, C#, jQuery
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: