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...
https://www.programming-free.com/2013/05/aspnet-ajax-cascading-dropdownlist-with.html
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
Subjects.cs
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.
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.
That is all. See below screenshots or try the live demo to know how the outcome of the above implementation will look like,
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!!
>
Very Nice and useful article.Keep going
ReplyDeletegood stuff. nicely done too.
ReplyDeleteThank you!
DeleteGood work Priya Darshini
ReplyDeleteThank you!
Deletevery good initiative from you.
ReplyDeleteHi Priya
ReplyDeleteI 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
Please explain your problem and post your code at http://forums.asp.net for immediate help on this by experts.
DeleteHi 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.
ReplyDeleteThanks for your help in advance !
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.
ReplyDeleteHi,
DeleteYou 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
Thanks for the quick response. I'll try it and let you know.
ReplyDelete//added these variables for lower levels criteria //
ReplyDeletevar 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);
});
});
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.
ReplyDeleteBut 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
$ddlSub.bind("change keyup", function () {
ReplyDeletealert($("select option:selected").val());
});
});
I think this bind never gets executed in your example or at least for me.
Very nice.Its very much useful.
ReplyDeleteLink to download source code?
ReplyDeleteIts great. work fine for me. very very useful article.
ReplyDeletein case of cascading dropdown the result is populating in 2 dropdowns instead of 1
ReplyDeletePlease Help How can i include this dropdownlist to my project
ReplyDeletec++ codes for beginners
ReplyDeleteLink to download code ?
ReplyDeleteNice information on .net
ReplyDeleteselenium training in Bangalore
selenium courses in Bangalore
selenium training in Marathahalli
selenium training institute in bangalore
best web development training in Bangalore
web development course in bangalore
best web development training in Bangalore
web development training in Marathahalli
techbindhu
I used to be able to find good advice from your articles.
ReplyDeletemobile service center banglore
Samsung Galaxy S8+ service center near me
oppo Find 7a authorized service center near me
oneplus 3 service center in whitefield
realme 2 service center in marathahalli
BECOME A DIGITAL MARKETING
ReplyDeleteEXPERT WITH US
COIM offers professional Digital Marketing Course Training in Delhi to help you for job and your business on the path to success.
+91-9717 419 413
8057555775
Digital Marketing Course in Laxmi Nagar
Digital Marketing Institute in Delhi
Digital Marketing training in Preet Vihar
Online Digital Marketing Course in India
Digital Marketing Institute in Delhi
Digital Marketing Institute in Delhi
Love Romantic
Digital Marketing Institute In Greater Noida
Digital Marketing Institute In Alpha greater noida
Excellent post! We will be linking to this great article on our website. Keep up the good writing.
ReplyDeleteHuawei mobile LCD screen replacement in Bangalore
Vivo mobile LCD screen replacement in Bangalore
Motorola mobile LCD screen replacement in Bangalore
Asus mobile LCD screen replacement in Bangalore
LG Stylus 2 mobile LCD screen replacement in Bangalore
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
ReplyDeleteGood post thanks for share information.
AppValley VIP APK
Cami Elliott
lola Iolani Momoa
rolling paper alternatives
Mp3boo
free edu email
This comment has been removed by the author.
ReplyDeleteWhile 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? 토토사이트모음
ReplyDeletePretty 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.
ReplyDeleteAmazing issues here. I am very glad to see your post. Thanks so much and I’m taking a look forward to contact you.
ReplyDelete휴게텔
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"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?
ReplyDeleteI have a presentation subsequent week, and I’m at the search for such info."
스포츠마사지
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.
ReplyDeletebursa
ReplyDeleteçankırı
çorum
denizli
diyarbakır
edirne
elazığ
erzincan
erzurum
ReplyDeleteYour posts are always informative for us.
disneyplus.com login/begin | showtime anytime/activate | aka.ms/remoteconnect
ReplyDeleteThanks for giving the informative articles. I hope you will give more articles like this.
Crypto.com Log In | MetaMask Log In
How to Unsend an Email in Outlook App?
ReplyDeleteCheck 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.
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
ReplyDeleteThank you for sharing the knowledgeable article.
ReplyDeleteMetamask Sign in | Metamask Wallet Login | www.Coinbase.com Login
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먹튀검증커뮤니티 games you have the best chance at winning
ReplyDeletePancake 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.
ReplyDeleteGo 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.
ReplyDeleteAtomic Wallet |
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.
ReplyDeleteuphold wallet|uphold exchange|blockfi wallet|block fi wallet | blockfi app |
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.
ReplyDeleteFor More About:- Binance smart chain wallet$Kucoin.com$Kucoin Wallet
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.
ReplyDeleteRead 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.
metamask sign in
ReplyDeleteThis is really helpful info. Thanks for sharing a wonderful content!
ReplyDeleteMetamask Sign in | aol mail | Pro Coinbase
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.
ReplyDeleteSincerely 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.
ReplyDeleteSincerely 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.
ReplyDeleteIf 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.
ReplyDeleteCertainly! 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.
ReplyDeleteAaijidevelopers.
Thanks for sharing these information sites please vesit on given this site : Trezor Live
ReplyDelete|| Trezor App
This comment has been removed by the author.
ReplyDeleteDefos Design We specialize in retail design agencies that can help any business thrive. We know how important it is to make the most of your retail space.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteImplementing an AJAX Cascading DropDownList with autosuggest in ASP.NET using jQuery enhances the user experience by providing dynamic data updates and predictive text input. This approach minimizes page reloads and makes data selection more intuitive
ReplyDeletehttps://hexacorp.sharepoint.com/:w:/r/sites/sales%26marketing/DMActivities/1%20-%20HexaCorp%20Website%20Maintenance/Blogs/28%20-%20Power%20Tips%209%20Things%20to%20Consider%20While%20Using%20Microsoft%20Power%20Apps.docx?d=wb56854183d8c42eb897ad4956015c155&csf=1&web=1&e=ehG0JX