ASP.NET: AJAX Cascading Dropdownlist with Autosuggest using Jquery

DEMO Cascading dropdownlists are a set of dropdownlist controls in which each dropdownlist is populated based on another dropdownlist...




Cascading dropdownlists are a set of dropdownlist controls in which each dropdownlist is populated based on another dropdownlist's selected item and the best approach to implement this is without refreshing the whole page in AJAX way. There are several ways in which we can achieve this such as using AJAX Toolkit's CascadingDropdown extender along with ASP.NET dropdownlist, using dropdownlist in an UpdatePanel and using jquery to make AJAX calls to populate dropdownlist. One more feature that is desirable in a dropdownlist is the autocomplete functionality, that can help the user to get to the right option without scrolling much especially when there are lot of items in the dropdownlist.

In this post, I am going to explain with an example on how to implement cascading dropdownlist using jquery and apply autocomplete feature using Select2 jquery plugin in the client side. We are going to populate the dropdownlists by making jquery ajax calls to server side method(WebMethod) and enable autocomplete feature in client side using Select2 jquery plugin.
1.  First of all let us download all the required libraries,

a. jQuery
b. Select2

2. Place the above downloaded libraries inside your asp.net project folder.


3. Let us now create two model classes, that would serve the data required for the dropdownlists. The first dropdownlist will contain items that are departments and the other will contain items that are subjects corresponding to the department that is selected in the first dropdownlist. Department dropdownlist will be populated on page load and subjects dropdownlist will be populated whenever an item is selected in the department dropdownlist by making ajax calls to the server.

Department.cs

namespace CascadingAutoCompleteSample
{
    public class Department
    {
        public string dptName { get; set; }
        public string dptAliasName { get; set; }

        public List<Department> GetDepartment()
        {
            return new List<Department>
            {
                new Department {
                    dptName = "Aeronautical Engineering",
                    dptAliasName = "AE"
                },
                new Department {
                    dptName = "Biomedical Engineering",
                    dptAliasName = "BME"
                },
                new Department {
                    dptName = "Computer Science Engineering",
                    dptAliasName = "CSE"
                },
                new Department{
                    dptName = "Information Technology",
                    dptAliasName = "IT"
                },
                 new Department{
                    dptName = "Mechanical Engineering",
                    dptAliasName = "MECH"
                },
                 new Department{
                    dptName = "Electronics and Communication Engineering",
                    dptAliasName = "ECE"
                }
            }.ToList();
        }
    }
}

Subjects.cs

namespace CascadingAutoCompleteSample
{
    public class Subjects
    {
        public string deptAliasName { get; set; }
        public string subName { get; set; }
        public string subAliasName { get; set; }

        public List<Subjects> GetSubjects()
        {
            return new List<Subjects>
            {
                new Subjects {
                    deptAliasName="AE",
                    subName = "Fluid Mechanics",
                    subAliasName = "FM"
                },
                new Subjects {
                    deptAliasName="AE",
                    subName = "Aircraft System",
                    subAliasName = "AS"
                },
                new Subjects {
                    deptAliasName="AE",
                    subName = "Helicopter Theory",
                    subAliasName = "HT"
                },
                new Subjects {
                    deptAliasName="BME",
                    subName = "Bio Analytical Techniques",
                    subAliasName = "BAT"
                },
                new Subjects {
                    deptAliasName="BME",
                    subName = "Bio Signal Processing",
                    subAliasName = "BSP"
                },
                new Subjects {
                    deptAliasName="CSE",
                    subName = "Data Structures & Algorithms",
                    subAliasName = "DSA"
                },
                new Subjects{
                    deptAliasName="CSE",
                    subName = "Computer Architecture",
                    subAliasName = "CO"
                },
                 new Subjects{
                    deptAliasName="CSE",
                    subName = "Artificial Intelligence",
                    subAliasName = "AI"
                },
                 new Subjects{
                     deptAliasName="CSE",
                    subName = "Fundamentals of Computing",
                    subAliasName = "FOC"
                },
                new Subjects{
                     deptAliasName="IT",
                    subName = "Numerical Methods",
                    subAliasName = "NM"
                },
                new Subjects{
                     deptAliasName="IT",
                    subName = "Fundamentals of Computing",
                    subAliasName = "FOC"
                },
                new Subjects{
                    deptAliasName="IT",
                    subName="Priciples of Communication",
                    subAliasName="POC"
                },
                new Subjects{
                     deptAliasName="MECH",
                    subName = "Measurements and Controls",
                    subAliasName = "MC"
                },
                new Subjects{
                     deptAliasName="MECH",
                    subName = "Machine Tools",
                    subAliasName = "MT"
                },
                new Subjects{
                     deptAliasName="ECE",
                    subName = "Electronic Devices & Circuits",
                    subAliasName = "EDC"
                },
                new Subjects{
                     deptAliasName="ECE",
                    subName = "Electro Magnetic Theory",
                    subAliasName = "EMT"
                }
                
            }.ToList();
        }
    }
}

Data is hard coded in these classes, you can also modify this to fetch items from a database if you prefer.

4. Let us create an aspx page with two dropdownlists and script to make ajax calls to server to populate one of it based on the other. The script will also convert these dropdownlists in to rich dropdownlists that enables the user to search for an item in it.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Cascading AutoComplete DropDownlist using jQuery</title>
    <link href="Styles/select2.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.9.1.js"></script>
    <script src="Scripts/select2.js"></script>
    <script type="text/javascript">
        $(function () {
            var $ddl = $("select[name$=ddlDepartment]");
            $ddl.select2();
            var $ddlSub = $("select[name$=ddlSubject]");            
            $ddl.focus();
            $ddl.bind("change keyup", function () {
                loadSubjects($("select option:selected").val());
                $ddlSub.fadeIn("slow");


            });
        });
        function loadSubjects(selectedItem) {
            $.ajax({
                type: "POST",
                url: "CascadingAutocomplete.aspx/GetSubjectList",
                data: "{deptAliasName:'" + selectedItem + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: function (data) {
                    printSub(data.d);

                },
                error: function (xhr, status, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);

                }
            });
        }
        function printSub(data) {
            $("select[name*=ddlSubject] > option").remove();
            $("select[name*=ddlSubject]").append(
                $("<option></option>").val("Select Subject").html("Select Subject")
                );
            for (var i = 0; i < data.length; i++) {
                $("select[name*=ddlSubject]").append(
                    $("<option></option>").val(data[i].subAliasName).html(data[i].subName)
                );
            }           
            $("#subjectdiv").css("display","block");
            $("select[name$=ddlSubject]").select2();
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align:center">
         <h1>Cascading AutoComplete in ASP.NET using jQuery</h1>
        Select Department : 
        <asp:DropDownList ID="ddlDepartment" runat="server" Width="280px">
        </asp:DropDownList>
        <br/>
        Select Subject :
      <asp:DropDownList ID="ddlSubject" runat="server" Width="280px" >           
        </asp:DropDownList>
       
    </div>       
    </form>
</body>
</html>

Let us take a close look on the jquery script that makes ajax calls to populate the second dropdownlist. The loadSubjects method is fired whenever an user selects or changes value in the first dropdownlist and makes ajax call to method that is declared as WebMethod in the code behind page(CascadingAutocomplete.aspx/GetSubjectList). Once the data is fetched from server side, printSub method in the above script updates user interface in this case the second dropdownlist with the response. Both the dropdownlists are enabled with autosuggest feature using select2 plugin.

5. Now in the code behind page let us write code that is called by the jquery script to fetch data for the Subjects dropdownlist. Note that to call a server side method, the method should be declared as a WebMethod.

using System.Web.Services;
using System.Web.Script.Services;


namespace CascadingAutoCompleteSample
{
    public partial class CascadingAutocomplete : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Department dept = new Department();
            List<Department> lstDept = dept.GetDepartment();
            ddlDepartment.DataSource = lstDept;
            ddlDepartment.DataTextField = "dptName";
            ddlDepartment.DataValueField = "dptAliasName";
            ddlDepartment.DataBind();
            ddlDepartment.Items.Insert(0, new ListItem("Select Department", "Select Department"));
            ddlDepartment.SelectedItem.Text = "Select Department";


        }


        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static List<Subjects> GetSubjectList(string deptAliasName)
        {
            Subjects sub = new Subjects();
            List<Subjects> lstSubs = sub.GetSubjects().Where(x => x.deptAliasName == deptAliasName).ToList();
            return lstSubs;
        }

    }
}

That is all. See below screenshots or try the live demo to know how the outcome of the above implementation will look like,




Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!
 
>

Subscribe to GET LATEST ARTICLES!


Related

Jquery 7915741274987572667

Post a Comment

  1. Very Nice and useful article.Keep going

    ReplyDelete
  2. very good initiative from you.

    ReplyDelete
  3. Hi Priya
    I try to used the above in of my page which included in master page, In that I am using jquery treeview plugin, I am facing some problems while implementing the selects().
    Can you please help regarding this.

    Thanks
    Prakash

    ReplyDelete
    Replies
    1. Please explain your problem and post your code at http://forums.asp.net for immediate help on this by experts.

      Delete
  4. Hi Priya- if I like to capture my selection i.e. Department and the Subject after user has chosen both, how can I do that? I am trying to implement this example but the issue I am having is to bind the capture the change keyup (user's selection) for the last dropdown list.

    Thanks for your help in advance !

    ReplyDelete
  5. Or to put it simply, how should I print (alert) chosen Department and Subject on the screen every time I change the department and/or subject.

    ReplyDelete
    Replies
    1. Hi,

      You can edit the script in this example like this to throw an alert when the user selects a department or subject,

      <script type="text/javascript">
      $(function () {
      var $ddl = $("select[name$=ddlDepartment]");
      $ddl.select2();
      var $ddlSub = $("select[name$=ddlSubject]");
      $ddl.focus();
      $ddl.bind("change keyup", function () {
      loadSubjects($("select option:selected").val());
      $ddlSub.fadeIn("slow");
      });
      //this alerts the selected subject
      $ddlSub.bind("change keyup", function () {
      alert($("select option:selected").val());
      });
      });
      function loadSubjects(selectedItem) {
      alert(selecteditem);// This alerts the selected department
      $.ajax({
      type: "POST",
      url: "CascadingAutocomplete.aspx/GetSubjectList",
      data: "{deptAliasName:'" + selectedItem + "'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      async: true,
      success: function (data) {
      printSub(data.d);

      },
      error: function (xhr, status, err) {
      var err = eval("(" + xhr.responseText + ")");
      alert(err.Message);

      }
      });
      }
      function printSub(data) {
      $("select[name*=ddlSubject] > option").remove();
      $("select[name*=ddlSubject]").append(
      $("<option></option>").val("Select Subject").html("Select Subject")
      );
      for (var i = 0; i < data.length; i++) {
      $("select[name*=ddlSubject]").append(
      $("<option></option>").val(data[i].subAliasName).html(data[i].subName)
      );
      }
      $("#subjectdiv").css("display","block");
      $("select[name$=ddlSubject]").select2();
      }
      </script>


      Hope this helps!

      Thanks,
      Priya

      Delete
  6. Thanks for the quick response. I'll try it and let you know.

    ReplyDelete
  7. //added these variables for lower levels criteria //
    var selectedDeptNbr;
    var selectedSubDeptNbr;
    var selectedClassNbr;
    var selectedSubClassNbr;
    $(function () {
    var $ddlDeptLst = $("select[name$=ddlDepartment]"); //dept
    var $ddlSubDeptLst = $("select[name$=ddlSubDepartment]"); //subdept
    var $ddlClassLst = $("select[name$=ddlClass]"); //class
    var $ddlSubClassLst = $("select[names$=ddlSubClass]"); //subclass
    $ddlDeptLst.select2();
    $ddlDeptLst.focus();
    $ddlDeptLst.bind("change keyup", function () {
    $("#classdiv").css("display", "none");
    $("#subclassdiv").css("display", "none");
    selectedDeptNbr = $('#deptdiv option:selected').val();
    loadSubDepts($('#deptdiv option:selected').val());
    $ddlSubDeptLst.fadeIn("slow");
    $ddlSubDeptLst.focus();
    });

    $ddlSubDeptLst.bind("change keyup", function () {
    $("#subclassdiv").css("display", "none");
    selectedSubDeptNbr = $('#subdeptdiv option:selected').val();
    loadClasses($("#subdeptdiv option:selected").val());
    $ddlClassLst.fadeIn("slow");
    });

    $ddlClassLst.bind("change keyup", function () {
    selectedClassNbr = $('#classdiv option:selected').val();
    loadSubClasses($("#classdiv option:selected").val());
    alert("Your selection is :" + selectedDeptNbr + "-" + selectedSubDeptNbr + "-" + selectedClassNbr);
    $ddlSubClassLst.fadeIn("slow");

    });
    $ddlSubClassLst.bind("change keyup", function () {
    alert("Your selection is :" + selectedDeptNbr + "-" + selectedSubDeptNbr + "-" + selectedClassNbr + "-" + selectedSubClassNbr);
    });
    });

    ReplyDelete
  8. in the above example,everything works just fine but the last bind i.e. $ddlSubClassLst.bind does not even get called and it does not even reach to alert() call either.

    But my alert one step above i.e.

    alert("Your selection is :" + selectedDeptNbr + "-" + selectedSubDeptNbr + "-" + selectedClassNbr);

    works just find returned the value for dept,subdept and as well as selected class

    ReplyDelete
  9. $ddlSub.bind("change keyup", function () {
    alert($("select option:selected").val());
    });
    });

    I think this bind never gets executed in your example or at least for me.

    ReplyDelete
  10. Link to download source code?

    ReplyDelete
  11. Its great. work fine for me. very very useful article.

    ReplyDelete
  12. in case of cascading dropdown the result is populating in 2 dropdowns instead of 1

    ReplyDelete
  13. Please Help How can i include this dropdownlist to my project

    ReplyDelete
  14. Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have 먹튀검증 Hi. I think I have found you just the right time 먹튀검증

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. While looking for articles on these topics, I came across this article on the site here. As I read your article, I felt like an expert in this field. I have several articles on these topics posted on my site. Could you please visit my homepage? 토토사이트모음


    ReplyDelete
  17. Pretty component to content. I simply stumbled upon your blog and in accession capital to say that I get in fact enjoyed account your weblog posts 야한소설 . Any way I will be subscribing on your feeds or even I success you access constantly fast.

    ReplyDelete
  18. Amazing issues here. I am very glad to see your post. Thanks so much and I’m taking a look forward to contact you.

    휴게텔

    ReplyDelete
  19. Great blog right here! Additionally your site a lot up very fast! What host are you the use of? Can I am getting your associate hyperlink in your host? I wish my web site loaded up as fast as yours 횟수 무제한 출장

    ReplyDelete
  20. "Impressive Thanks for the post! Carry on, don’t stop! Thanks for any other great article. The place else could anybody get that kind of info in such a perfect means of writing?
    I have a presentation subsequent week, and I’m at the search for such info."

    스포츠마사지

    ReplyDelete
  21. This way they don't have to spend time opening hundreds of card packs or participating in modes they don't like to complete challenges. The way to get a lot of Coins is also very simple, that is to Buy FUT 22 Coins at UTnice. UTnice supports a variety of secure payment methods, and their website provides Comfort Trade delivery methods, you only need to pay and enter the necessary information correctly. Their delivery team will help you complete the rest.

    ReplyDelete
  22. I Went From $5 To A Knife! 안전메이저놀이터 토토사이트 메이저놀이터리스트

    ReplyDelete

  23. Thanks for giving the informative articles. I hope you will give more articles like this.
    Crypto.com Log In | MetaMask Log In

    ReplyDelete
  24. How to Unsend an Email in Outlook App?

    Check out the steps mentioned to know how to unsend an email in Outlook app. Select the sent items folder in the folder panel on the left of Outlook window. Here, open message that you want to recall and then double-click to open message. If you choose the message and it appears in reading panel then it will not allow to recall this message.If you have ribbon then choose actions and then recall this message from message tab. choose to delete unread copies of message or delete unread copies or replace it with the new one by clicking on OK. Lastly, if you are sending the replace message then compose new one and choose to send.


    How to Setup Bellsouth Email on iPhone?

    There are times when users have the query about how to setup Bellsouth email on iPhone then start by setting up your email. Now, launch the settings app on iPhone and choose mail, contacts, and calendar. Touch to add accounts under the accounts heading and choose other than account type. After that, click to add an email account. Now, enter your name, Bellsouth email address and password in the requested field. After that, you need to enter the Bellsouth email details in the requested fields. Now, choose to next to let your iPhone device check if settings are working properly or not. Lastly, you need to customize the email settings as per your personal preference.


    Troubleshooting Steps for Yahoo Not Working

    If you are an iPhone user then sometimes users do encounter with the issue of Yahoo not working. If you are the one facing same issue then check out the steps. For this, press and hold the power button along with volume up button. Within few seconds, you will see power-off slider. After that, drag the slider and let your device turn off properly. Now, to turn on press and hold the power button and then wait till the Apple logo appears. These are the steps that users need to follow to smoothly deal with the issue of Yahoo not working issue.

    How to Turn Off Outlook Notifications on Apple Watch?

    Check out the steps to know about to know how to turn off Outlook notifications on Apple Watch. If you don’t want to receive email notifications on Apple Watch, then you can smoothly turn it off by going to my watch (tab) > mail > custom > under alerts. You can access your iPhone settings by going to the settings application. After that, you can access notifications by going to the notifications section. The included section should contain a listing of Outlook. Lastly, to access Outlook and choose the tab. Lastly, these are the steps to turn off Outlook notifications on Apple Watch smoothly.

    ReplyDelete
  25. This is actually an realistic and wonderful records for all. Thanks for sharing this to us and additional power. Metamask log in | Crypto.com Log in

    ReplyDelete
  26. Your article is very good and useful, thank you for sharing. If you have and iPhone and don't know how to create a custom ringtones for iPhone, if yes then don't worry, you can very easily create your favorite ringtones with the help of these site, these iPhone ringtones site is the best for you, for more info you can read one article about create ringtones for iPhone, with the help of these you can create your own iPhone ringtone.

    ReplyDelete
  27. Pancake Swap allows users to earn an additional yield by staking supported liquidity provider (LP) tokens in one of its numerous yield farms. By participating in a yield farm, users earn a CAKE yield on their LP tokens. This is on top of the yields generated through transaction fees.

    ReplyDelete
  28. Go to Slope Wallet official website and select from Android or iOS for mobile application and select Chrome for desktop. You can also go directly to the Chrome Store, Google Play, or App Store. Then, search "Slope Wallet" and install.
    Atomic Wallet |

    ReplyDelete
  29. Uphold is available on both desktop computers and smartphones, so to get started with this cryptocurrency exchange platform, you must either visit Uphold.com or find the uphold app in your phone’s app store.
    uphold wallet|uphold exchange|blockfi wallet|block fi wallet | blockfi app |

    ReplyDelete
  30. Thanks for giving such a wonderful informative information. The detailed read above has been fully-equipped to first, introduce you to the Kucoin App and then take you through exclusive details on the subject. Reading through the data piece above, you are now aware of all the pros and cons that an easily-created KuCoin login account could bring to you, along with significant details on the United States’ jurisdiction that doesn’t allow the exchange to function there and also the list of major crypto available on it.
    For More About:- Binance smart chain wallet$Kucoin.com$Kucoin Wallet

    ReplyDelete
  31. Nice information! Read Crypto trading is soaring to new heights every other day and owing to this, a lot of new and old trading Kucoin Wallet exchanges are coming to the front with their own trading services.
    Read through this amazingly put data piece to learn about the Binance Chain Wallet, which is created to deliver utmost safety to the official Binance token.

    ReplyDelete
  32. This is really helpful info. Thanks for sharing a wonderful content!
    Metamask Sign in | aol mail | Pro Coinbase

    ReplyDelete
  33. I am thankful to you for sharing this plenty of useful information. Are you searching for a love language quiz? If yes, then I know one site about the rice purity test. To understand your partner’s favorite way to show your love, the Love Language Quiz works to keep your relationship on the right track. So go and give this test.

    ReplyDelete
  34. Sincerely very satisfied to say, your submit is very exciting to examine. Unlock clash royal tournaments With [url= https://miarroba.com/masterroyaleapk]Master Royale[/url]private server, one can unlock various tournaments and participate in tournaments against other players. you can view the full article for the steps.

    ReplyDelete
  35. Sincerely very satisfied to say, your submit is very exciting to examine. Unlock clash royale tournaments with Master Royale private server, one can unlock various tournaments and participate in tournaments against other players. you can view the full article for the steps.

    ReplyDelete
  36. If you want to know how to unlock free rewards? if yes, then you can read this article about master royale apk It is the simplest and fastest way for unblocking clash royale's rewards within a few seconds. So, you must download the master royale apk, free of cost.

    ReplyDelete
  37. Certainly! However, I'll need more specific information about the blog you'd like to comment on. Please provide the title or topic of the blog, and I can help you craft a relevant and engaging comment.
    Aaijidevelopers.

    ReplyDelete
  38. Thanks for sharing these information sites please vesit on given this site : Trezor Live
    || Trezor App

    ReplyDelete
  39. This comment has been removed by the author.

    ReplyDelete

emo-but-icon

SUBSCRIBE


item