Use ASP.NET AJAX Cascading Drop Down Control to Access a Database

This video demonstrates how ASP.NET’s standard DropDownList can become AJAX-enabled using the CascadingDropDown control extender from the ASP.NET AJAX Control Toolkit. You will also see how easy it is for a web form to draw data from a Database.

Presented by Joe Stagner

Duration: 32 minutes, 23 seconds

Date: 13 March 2008

Watch the video   |   Download the video   |   Get VB code  or  C# code

Video downloads: WMV | Zune | iPod | PSP | MPEG-4 | 3GP

Audio downloads: AAC | WMA | MPEG-4 | MPEG-3 | MPEG-2

Comments : 38

Leave a Comment

liga : On March 14, 2008 10:55 AM said:

I need cascading dropdownlists for my current project. My database hierarchy structure is designed to have an unspecified indent level. So I might need 3 dropdownlists.. maybe 4, maybe just 2.

Thanks for the introduction :-)

JoeStagner : On March 15, 2008 12:43 PM said:

That's an interesting scenario.

I don't have any code that does this, though I'll put it on my list.

Dynamically Adding conrols in ASP.NET somewhat difficult becuase the added controls are not added to any page state mechanism.

You certainly can inject additional DropDowns programatically into the page but you'll need to recreate those additions in the page_init method so postbacks don't remove them.

edirgaria : On March 16, 2008 3:32 PM said:

Joe,

I don't quite understand about this tool needs to use Web Service to pick up data from database. How come this extender doesn't provide DataSourceID attributes to just call the SQLDataSource control to get the data feed instead of going through so much coding with Web Service?

I just think this AJAX control is just making developer to create more codes rather than simplify the coding process for having a cascading dropdown control. We can have a series of cascading dropdown controls by using SQLDataSource wrapped inside the UpdatePanel control, why would we need this AJAX one which requires us to go through Web Service to get data from the database.

Please correct me if I am wrong.

Thank you,

Erik

omardayya : On March 17, 2008 6:54 AM said:

I liked this video a lot man, thanks a lot dear Joe. You have used a lot of techniques in this video, and it was so benificial to watch it. Thanks a lot man

orange_square : On March 18, 2008 10:00 AM said:

I do share the same opinion with edirgaria, although maybe I didn't really get the essence. Can you please list the advantages (disadvantages) of using this technique over the UpdatePanel one?

Thanks

Radu

Nezdet : On March 20, 2008 7:33 AM said:

Hi Joe

Very very good video.. this has helped me alot.

But i need to know one thing. What if the javascript is turned of the ajac-cotrols doesn't work!!!!

How do I handle so the page works as standard aspx if javascript is disabled. Are there any examples on that??

JoeStagner : On March 20, 2008 5:24 PM said:

There are a couple of reasons for using service methods instead of UpdatePanel.

1.) UpdatePanel is WAY less efficient since it does a complete page postback and executes the complete .aspx pafe lifecycle.

2.) YOu can execute much more server side logic than a simple parametric database query.

As to JavaScript.....

If the user doesn't have JavaScript enabled then there is no AJAX. You need to post back after every selection (which you can't do automaticaly since there is no JavaScript) and build an updated page each time.

Nezdet : On March 20, 2008 9:14 PM said:

What you are saying is that I should also write code in the server-side(aspx.cs) in the load_event that retrives data from the database.

But what if javascript is enabled. It retrives data two times.. one from the Load_event(Serverside) and the secondtime it gets from the Servicefile(constructed for AJAX-controls)????

Thanks

JoeStagner : On March 22, 2008 11:25 AM said:

You asked what to do it Javascript was turned OFF.

If JavaScript is on then you just do ASP.NET AJAX.

Nezdet : On March 22, 2008 12:15 PM said:

yes that is what Iam asking for. How do I check if javascript is on so I can use ajax? Iam using services like your example.

Nezdet : On March 23, 2008 9:52 PM said:

Why are you not creating a video on how to detect javascript?? is it not important? Cause I have asked and searched, havent found any good information...

JoeStagner : On March 25, 2008 2:30 PM said:

No need for a video.

Just use the code here:

www.codeproject.com/.../Javascript_Detection.aspx

Jnaneshwar : On March 28, 2008 7:05 AM said:

Hi Joe,

I'm trying to implement Cascading DDLs with DB using  Categories and Products tables of Northwind db.

I've two DDLs - category & products and 2 CCDs - ccdCategory and ccdProducts.

I'm getting [Method Error 500] when page loads.

I'm using Web Developer 2005 Express Edition.

Can you please tell me why this happens?

But web service is working correctly.

Jnaneshwar : On March 28, 2008 7:28 AM said:

Hi Joe,

I saw your vedio and was trying to implement Cascading DDLs with DB using  Categories and Products tables of Northwind db.

I've two DDLs - category & products and 2 CCDs - ccdCategory and ccdProducts.

I'm getting [Method Error 500] in Category DDL when page loads.

I've set ServiceMethod & ServicePath properties correctly.

And also the required attributes in web service file.

I'm using Web Developer 2005 Express Edition.

Can you please tell me why this happens?

But web service is working correctly.

Madhukeshwar : On March 31, 2008 3:25 AM said:

Hi joe,

I never thought that implementing ajax in .net is soo easy and interesting.Ya Microsoft makes every thing powerful and easy to implement.I m proud of Microsoft.

And Joe all ajax videos posted by u are just fantastic.

This will help many.Thank u very much.

can u tell me difference between "Atlas" and "Ajax Extension 1.0". Which one should i install to use??

waiting for reply.............

JoeStagner : On March 31, 2008 9:32 AM said:

Many THANKS !

I's so rewarding when folks are able to learn from the work I/we do.

BTW - Atlas was just the project name that we used before we released. You should be using the "ASP.NET Extensions for AJAX 1.0".

To Jnaneshwar: You're seeing a 500 Server error ?

Ths is useually an error in the Web Service code and can be seen if the Service Class is not decorated with the ScriptService attribute.

jonathanrufus : On April 03, 2008 3:27 AM said:

I had a look at AutoComplete Extender, Which OnTextChanged is returning some values in a list box, I want that to be checkboxlist to enable multiple selections. How can that be done

cluce : On April 04, 2008 10:11 AM said:

Could I populate a checkbox list with the last cascading drop down list using this method?  I need two drop down lists and one checkbox list for a user to make selections.

JoeStagner : On April 14, 2008 8:19 PM said:

Not as it exists now, but since it's open source you could fork your own version of the control.

wcygan : On April 21, 2008 10:08 AM said:

Joe: terrific example. One question: once these controls are set up and a page postback is done (after completing the rest of the selections on a page), the viewstate of the dropdown list controls seems to get lost. I have seen some references to doing some work OnInit to preserve viewstate, but if the access to the database is all being handled through the extender control properties and a web service, there is not a lot being done that could be moved to "OnInit". Is there a way to preserve viewstate for the cascading dropdowns when returning after a page postback?

Thanks, Walt

Hideyoshi : On May 06, 2008 10:27 PM said:

Dear Joe,

I'm totally new in AJAX, from this video, I would like to know the code:

Public Fuction GetMakes(byval knownCategoryValues as String, ByVal category As string) As CascaddingDropDownNameValue()

'implementing

End Function

1) Is that the knownCategoryvalues is the reserve word?

2) the function is pass in 2 parameters from where?

3) from the implementing part, the makesValues.add () NewCascadingDropDownValue (row("...").tostring(), row("...").tostring())

the carId return parameter is to pass in to the cascading model's as knownCategoryValue?

4)from the next webmethod: Model

stringDictionary is used when we need to get parameter from parent control? for database?

5)what is that means by Cascadingdropdown.ParseKnownCategoryValuesString(knownCateg oryValue)?

6)if my MakeID is a string value,in the if method, i should put "...or (Not char.tryParse(kv("Make"),makeID)) Then ..."

Hope to hear you soon.Thank you

Hideyoshi : On May 06, 2008 11:52 PM said:

from the movie above, i would like to know more details about it. Since i'm totally new to ajax,I am so hunger for that...

1) the knowCategoryValues a parameter that sent from where? Shall we use another name to replace it?

2) the string dictionary is act like an abstract table to get values knownCategoryValues from the parent control?

3)instead of use integer as a makeID, I use string as my make ID, then may i write "...Or (Not Char.TryParse(kv("SupplierID"), suppID))) Then ..."?

Hope to hear reply from anyone of you. Thanks.

Hideyoshi : On May 06, 2008 11:53 PM said:

Y i'm not able to leave a comment here?

airbornedude : On May 08, 2008 7:21 PM said:

METHOD 500 really makes CascadingDropDown a bad thing.

I have wasted to much time trying to trouble shoot this.

airbornedude : On May 14, 2008 4:45 PM said:

Joe,

   I have done this,"Ths is usually an error in the Web Service code and can be seen if the Service Class is not decorated with the ScriptService attribute."  But still get Method 500....   Should I abandon the Ajax thing and go back to the old way?  I hate to do that, but it looks like I might.

   I am curious, I saw your video of the debugging JavaScript in VS-2008.  I received a free copy from DevConnections and I was thinking of installing it.  Would I be able to trouble shoot this better if I had VS-2008?

landistols : On May 27, 2008 5:11 AM said:

Dear Joe,

I would like to populate my region dropdown list depending on my country dropdown list value. I would like to use the Cascading dropdown list - AJAX.Is there any way of doing this without having to use a Webservice? I would appreciate your help.

JoeStagner : On May 27, 2008 1:40 PM said:

Landistols - how else you you indend to dynamicaly fetch data from the server ?

Airborne - Email me directly and I'll see if I can help you find the bug.

Inno101 : On May 28, 2008 9:19 AM said:

Hi,

Been looking for this video tutorial for ages. Thanks for supplementing the xml source data tutorial.

I'm wondering of you can use a Datareader instead of a dataset?

bohunkus : On May 29, 2008 4:08 PM said:

Joe,

Thanks for this video! Really helped me out! I'm having 1 issue because I'm using a MasterPage. The child CDD can't find the parent CDD. I checked the HTML (view source) and the id of the parent is ctl00_ContentPlaceHolder1_cddCustomers. So, I used that in the child CDD, but no joy. Then I tried ctl00$ContentPlaceHolder1$cddCustomers, but still no joy.

How to I get this to work with a MasterPage?

Thanks in advance!

Chris

bohunkus : On May 29, 2008 4:13 PM said:

Doh!  Why is it when you post a question, just after you hit the Submit button, you have an idea that corrects your problem?! ha!

I figured out I should be trying to locate the parent DDL not the parent CDD! Thanks again for the video!

Chris

dude9er : On June 06, 2008 3:24 PM said:

I want two drop downs, state and county. When the first (table1) and second (table2) dropdowns are selected I want to display/write a list of contacts (table3) associated with the DD's. How can I do this using the above tutorial?

Lacidian : On July 21, 2008 6:38 PM said:

I have the same question as (Hideyoshi : On May 06, 2008 10:27 PM).

What I am trying to understand is the data flow of the controls and what I can easily manipulate and what is to be constant (assumed).

Specifically, I ran debug on the web service and I gathered the output:

All web services designed to interact w/ ajax cascadingdropdown boxes need to be in this pre-determined format. CascadingDropDownNameValue().

Which is actually just a 2 dimensional array [makeValues.ToArray()]in a xml format.

So testing the web service in this way would produce the following xml.

localhost/.../GetMakes

example paramters

knownCategoryValues:(empty string)

category:Make

returns:

 <?xml version="1.0" encoding="utf-8" ?>

- <ArrayOfCascadingDropDownNameValue xmlns:xsi="www.w3.org/.../XMLSchema-instance" xmlns:xsd="www.w3.org/.../XMLSchema" xmlns="http://tempuri.org/">

- <CascadingDropDownNameValue>

 <name>Acura</name>

 <value>1</value>

 <isDefaultValue>false</isDefaultValue>

 </CascadingDropDownNameValue>

- <CascadingDropDownNameValue>

 <name>Audi</name>

 <value>2</value>

 <isDefaultValue>false</isDefaultValue>

 </CascadingDropDownNameValue>

- <CascadingDropDownNameValue>

 <name>BMW</name>

 <value>3</value>

 <isDefaultValue>false</isDefaultValue>

 </CascadingDropDownNameValue>

 </ArrayOfCascadingDropDownNameValue>

My question is the same:

1) Is knownCategoryvalues a reserved word for interacting with web services designed for the control group (CascadingDropDow)?

2> How is it populated or is the answer assumed becaused it is part of the AJAX control. In other words, "this control is just that way, move on" .

I do plainly see where it gets the category field (data) from.

<ajaxToolkit:CascadingDropDown ID="cddMakes"                         runat="server"                                        TargetControlID="ddlMakes"

Category="Make"

so Any help in explaning "knownCategoryvalues" would be appreciated.

thanks,

-Doug Lubey of Louisiana

yashoc : On July 31, 2008 9:56 AM said:

Hi,

Thank you for this informative example.

I'm personnally trying to do a hierarchy structure with the cascading drop down but unable to do so. I'm using three times the same web service call with the different parent Ids. It works fine for the first and second ddl but for the third I always get a Method error and it changes. Sometimes it's 500, others it's 12030 and other it's 12031...

Any clues on how this can be done? Is there something I'm missing about the calls?

yashoc : On July 31, 2008 12:25 PM said:

Somehow it works now.

macupryk : On August 03, 2008 11:42 PM said:

I need to populate the cddDay where it takes two parameters from the other cascading drop downs

GetDayList ==> how should i modify the below code for this to work.

<ajaxToolkit:CascadingDropDown ID="cddMonth" runat="server" Category="Month"

               TargetControlId="ddlMonth"

               LoadingText="[Loading Months...]"

               ServicePath="../LocationService.asmx"

               ServiceMethod="GetMonthList" Enabled="True" />

           <ajaxToolkit:CascadingDropDown ID="cddYear" runat="server" Category="Year"

               TargetControlId="ddlYear"

               LoadingText="[Loading Year...]"

               ServicePath="../LocationService.asmx"

               ServiceMethod="GetYearList" Enabled="True" />

           <ajaxToolkit:CascadingDropDown ID="cddDay" runat="server" Category="Day"

               TargetControlId="ddlDay"

               LoadingText="[Loading Year...]"

               ServicePath="../LocationService.asmx"

               ServiceMethod="GetDayList" Enabled="True" />

       </td>

       <td align="left" bordercolor="#f6cccc" height="35" style="width: 60%">

         <asp:DropDownList style="position: static" Font-Size="Smaller" Font-Bold="true" id="ddlMonth" Runat="Server"></asp:DropDownList>&nbsp;

         <asp:DropDownList style="position: static" Font-Size="Smaller" Font-Bold="true" id="ddlDay" Runat="Server"></asp:DropDownList>&nbsp;

         <asp:DropDownList style="position: static" Font-Size="Smaller" Font-Bold="true" id="ddlYear" Runat="Server"></asp:DropDownList>&nbsp;

 [WebMethod(Description = "Populate a year list.")]

   [System.Web.Script.Services.ScriptMethod]

   public AjaxControlToolkit.CascadingDropDownNameValue[] GetYearList(string knownCategoryValues, string category)

   {

       List<CascadingDropDownNameValue> yearList = new List<CascadingDropDownNameValue>();

       // Year list can be changed by changing the lower and upper

       // limits of the For statement

       int i = 1;

       for (int intYear = DateTime.Now.Year - 18; intYear >= DateTime.Now.Year - 99; intYear--)

       {

           yearList.Add(new CascadingDropDownNameValue(intYear.ToString(), (i++).ToString()));

       }

       return yearList.ToArray();

   }

   /////////////////////////////////////////////////////////// ////////////////////////////

   [WebMethod(Description = "Populate a month list.")]

   [System.Web.Script.Services.ScriptMethod]

   public AjaxControlToolkit.CascadingDropDownNameValue[] GetMonthList(string knownCategoryValues, string category)

   {

       List<CascadingDropDownNameValue> monthList = new List<CascadingDropDownNameValue>();

       monthList.Add(new CascadingDropDownNameValue("January", "1"));

       monthList.Add(new CascadingDropDownNameValue("February", "2"));

       monthList.Add(new CascadingDropDownNameValue("March", "3"));

       monthList.Add(new CascadingDropDownNameValue("April", "4"));

       monthList.Add(new CascadingDropDownNameValue("May", "5"));

       monthList.Add(new CascadingDropDownNameValue("June", "6"));

       monthList.Add(new CascadingDropDownNameValue("July", "7"));

       monthList.Add(new CascadingDropDownNameValue("August", "8"));

       monthList.Add(new CascadingDropDownNameValue("September", "9"));

       monthList.Add(new CascadingDropDownNameValue("October", "10"));

       monthList.Add(new CascadingDropDownNameValue("November", "11"));

       monthList.Add(new CascadingDropDownNameValue("December", "12"));

       return monthList.ToArray();

   }

   /////////////////////////////////////////////////////////// ////////////////////////////

   [WebMethod(Description = "Populate a days list for a specific month and year.")]

   [System.Web.Script.Services.ScriptMethod]

   public AjaxControlToolkit.CascadingDropDownNameValue[] GetDayList(string knownCategoryValues, string category, int year, int month)

   {

       List<CascadingDropDownNameValue> dayList = new List<CascadingDropDownNameValue>();

       int NumberOfDays = DateTime.DaysInMonth(year, month);

       for (int day = 1; day <= NumberOfDays; day++)

       {

           dayList.Add(new CascadingDropDownNameValue(day.ToString(), day.ToString()));

       }

       return dayList.ToArray();

   }

   /////////////////////////////////////////////////////////// //////////////////////////////

torr6420 : On August 05, 2008 1:30 PM said:

Hello!

I wrote a classic ASP application that has 4 dropdown lists using javascript, the first is the driver that fills the other three, and their values are embedded in each of them. They are used for imputing and also for editing the data that comes from a database. I don’t know how to integrate javascript into ASP.NET. After looking at your videos and searching in the web I am still lost as to what to do.

Can you offer some guidance?.

Thanks

cv_vikram : On August 07, 2008 4:17 PM said:

A Good video..thanks

kbolick827 : On August 08, 2008 11:43 AM said:

I am getting the following error when I view in browser and have no clue what it means.  Any help would be appreciated.  Thanks.

Unable to cast object of type 'AjaxControlToolkit.CascadingDropDown' to type 'System.Web.UI.WebControls.DropDownList'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'AjaxControlToolkit.CascadingDropDown' to type 'System.Web.UI.WebControls.DropDownList'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:

[InvalidCastException: Unable to cast object of type 'AjaxControlToolkit.CascadingDropDown' to type 'System.Web.UI.WebControls.DropDownList'.]

  AjaxControlToolkit.CascadingDropDown.CascadingDropDown_Clie ntStateValuesLoaded(Object sender, EventArgs e) +89

  AjaxControlToolkit.ExtenderControlBase.LoadClientStateValue s() +268

  AjaxControlToolkit.ExtenderControlBase.Page_PreLoad(Object sender, EventArgs e) +28

  System.EventHandler.Invoke(Object sender, EventArgs e) +0

  System.Web.UI.Page.OnPreLoad(EventArgs e) +86

  System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1323

----------------------------------------------------------- ---------------------

Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433

Leave a Comment

You must be logged in to leave a comment. Click here to log in.

Page view counter
Microsoft Communities