Using CascadingDropDown with a Database (VB)
The CascadingDropDown control in the AJAX Control Toolkit extends a DropDownList control so that changes in one DropDownList loads associated values in another DropDownList. In order for this to work, a special web service must be created.
Overview
The CascadingDropDown control in the AJAX Control Toolkit extends a DropDownList control so that changes in one DropDownList loads associated values in another DropDownList. (For instance, one list provides a list of US states, and the next list is then filled with major cities in that state.) In order for this to work, a special web service must be created.
Steps
First of all, a data source is required. This sample uses the AdventureWorks database and the Microsoft SQL Server 2005 Express Edition. The database is an optional part of a Visual Studio installation (including express edition) and is also available as a separate download under https://go.microsoft.com/fwlink/?LinkId=64064. The AdventureWorks database is part of the SQL Server 2005 Samples and Sample Databases (download at https://www.microsoft.com/downloads/details.aspx?FamilyID=e719ecf7-9f46-4312-af89-6ad8702e4e6e&DisplayLang=en). The easiest way to set the database up is to use the Microsoft SQL Server Management Studio Express (https://www.microsoft.com/downloads/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796&DisplayLang=en) and attach the AdventureWorks.mdf
database file.
For this sample, we assume that the instance of the SQL Server 2005 Express Edition is called SQLEXPRESS
and resides on the same machine as the web server; this is also the default setup. If your setup differs, you have to adapt the connection information for the database.
In order to activate the functionality of ASP.NET AJAX and the Control Toolkit, the ScriptManager
control must be put anywhere on the page (but within the <form
> element):
[!code-aspxMain]
1: <asp:ScriptManager ID="asm" runat="server" />
In the next step, two DropDownList controls are required. In this sample, we use the vendor and contact information from AdventureWorks, thus we create one list for the available vendors and one for the available contacts:
[!code-aspxMain]
1: <div>
2: Vendor: <asp:DropDownList ID="VendorsList" runat="server"/><br />
3: Contacts: <asp:DropDownList ID="ContactsList" runat="server"/><br />
4: </div>
Then, two CascadingDropDown extenders must be added to the page. One fills the first (vendors) list, and the other one fills the second (contacts) list. The following attributes must be set:
ServicePath
: URL of a web service delivering the list entriesServiceMethod
: Web method delivering the list entriesTargetControlID
: ID of the dropdown listCategory
: Category information that is submitted to the web method when calledPromptText
: Text displayed when asynchronously loading list data from the serverParentControlID
: (optional) parent dropdown list that triggers loading of the current list
Depending on the programming language used, the name of the web service in question changes, but all other attribute values are the same. Here is the CascadingDropDown element for the first dropdown list:
[!code-aspxMain]
1: <ajaxToolkit:CascadingDropDown ID="ccd1" runat="server"
2: ServicePath="CascadingDropdown1.vb.asmx" ServiceMethod="GetVendors"
3: TargetControlID="VendorsList" Category="Vendor"
4: PromptText="Select Vendor" />
The control extenders for the second list need to set the ParentControlID
attribute so that selecting an entry in the vendors list triggers loading associated elements in the contacts list.
[!code-aspxMain]
1: <ajaxToolkit:CascadingDropDown ID="ccd2" runat="server"
2: ServicePath="CascadingDropdown1.vb.asmx" ServiceMethod="GetContactsForVendor"
3: TargetControlID="ContactsList" ParentControlID="VendorsList"
4: Category="Contact"
5: PromptText="Select Contact" />
The actual work is then done in the web service, which is set up as follows. Note that the [ScriptService]
attribute is used, otherwise ASP.NET AJAX cannot create the JavaScript proxy to access the web methods from client-side script code.
[!code-aspxMain]
1: <%@ WebService Language="VB" Class="CascadingDropdown1" %>
2: Imports System.Web.Script.Services
3: Imports AjaxControlToolkit
4: Imports System.Web
5: Imports System.Web.Services
6: Imports System.Web.Services.Protocols
7: Imports System.Collections.Generic
8: Imports System.Collections.Specialized
9: Imports System.Data.SqlClient
10: <ScriptService()> _
11: Public Class CascadingDropdown1
12: Inherits System.Web.Services.WebService
13: ' ...
14: End Class
The signature of the web methods called by CascadingDropDown is as follows:
[!code-vbMain]
1: Public Function MethodNameHere(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
So the return value must be an array of type CascadingDropDownNameValue
which is defined by the Control Toolkit. The GetVendors()
method is quite easy to implement: The code connects to the AdventureWorks database and queries the first 25 vendors. The first parameter in the CascadingDropDownNameValue
constructor is the caption of the list entry, the second one its value (value attribute in HTML???s <option
> element). Here is the code:
[!code-vbMain]
1: <WebMethod()> _
2: Public Function GetVendors(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
3: Dim conn As New SqlConnection("server=(local)\SQLEXPRESS; Integrated Security=true; Initial Catalog=AdventureWorks")
4: conn.Open()
5: Dim comm As New SqlCommand( _
6: "SELECT TOP 25 VendorID, Name FROM Purchasing.Vendor", conn)
7: Dim dr As SqlDataReader = comm.ExecuteReader()
8: Dim l As New List(Of CascadingDropDownNameValue)
9: While (dr.Read())
10: l.Add(New CascadingDropDownNameValue(dr("Name").ToString(),dr("VendorID").ToString()))
11: End While
12: conn.Close()
13: Return l.ToArray()
14: End Function
Getting the associated contacts for a vendor (method name: GetContactsForVendor()
) is a bit trickier. First of all, the vendor which has been selected in the first dropdown list must be determined. The Control Toolkit defines a helper method for that task: The ParseKnownCategoryValuesString()
method returns a StringDictionary
element with the dropdown data:
[!code-vbMain]
1: <WebMethod()> _
2: Public Function GetContactsForVendor(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
3: Dim VendorID As Integer
4: CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
For security reasons, this data must be validated first. So if there is a Vendor entry (because the Category
property of the first CascadingDropDown element is set to "Vendor"
), the ID of the selected vendor may be retrieved:
[!code-vbMain]
1: If Not kv.ContainsKey("Vendor") Or Not Int32.TryParse(kv("Vendor"),VendorID) Then
2: Throw New ArgumentException("Couldn't find vendor.")
3: End If
The rest of the method is fairly straight-forward, then. The vendor???s ID is used as a parameter for an SQL query that retrieves all associated contacts for that vendor. Once again, the method returns an array of type CascadingDropDownNameValue
.
[!code-vbMain]
1: Dim conn As New SqlConnection("server=(local)\SQLEXPRESS; Integrated Security=true; Initial Catalog=AdventureWorks")
2: conn.Open()
3: Dim comm As New SqlCommand("SELECT Person.Contact.ContactID, FirstName, LastName FROM Person.Contact,Purchasing.VendorContact WHERE VendorID=@VendorID AND Person.Contact.ContactID=Purchasing.VendorContact.ContactID",conn)
4: comm.Parameters.AddWithValue("@VendorID", VendorID)
5: Dim dr As SqlDataReader = comm.ExecuteReader()
6: Dim l As New List(Of CascadingDropDownNameValue)
7: While (dr.Read())
8: l.Add(New CascadingDropDownNameValue(dr("FirstName").ToString() & " " & dr("LastName").ToString(),dr("ContactID").ToString()))
9: End While
10: conn.Close()
11: Return l.ToArray()
12: End Function
Load the ASP.NET page, and after a short while the vendor list is filled with 25 entries. Pick one entry and notice how the second dropdown list is filled with data.
The first list is filled automatically (Click to view full-size image)
The second list is filled according to the selection in the first list (Click to view full-size image)
|