Javascript Cascading Dropdown in Asp.Net
There are various ways to get the cascading dropdown in the ASP.net. But the following is highly performance oriented approach. For fetching data the data is transferred from web server to client using web service. So the data transfer between server and client is very minimal. Thus you can experience the cascading very fast for a small to medium size of data.
This article needs Ajax Control kit. It needs to be downloaded separately.
Once downloaded, create a new website and select the Default.Aspx and then switch to design mode in the Web Form
CascadingDropDown In Web Form
While in design mode, open the tool box and right click and choose items. In the “Choose Toolbox Item” choose the downloaded AjaxControlToolKit.dll.
Now you will see a list Ajax controls in the tool Box.
Drag the Cascading Dropdown to the Web form.
Right click the website and add a web service named NorthwindDataService.asmx
In Web Service
import AjaxControlToolkit using Imports AjaxControlToolkit in the top
Add a new function named as GetCategories with the following paramters
CascadingDropDownNameValue: Ajax control kit needs this object back for loading data [name should not be changed]
Category: The category for filtering data[name should not be changed]
next step is to get data from DB
import System.Data using Imports System.Data in the top
import System.Data.SqlClient also
now get a datareader to fill up the CascadingDropDownNameValue list.
(I am not going to explain how to fetch the data from db as you can find the information in the asp.net data controls category)
Now its time to fill up the Cascading Dropdown control with the web service and web method we created just now.
CascadingDropDown Configuration
Fill up the following
ServicePath="NorthwindDataService.asmx"
ServiceMethod="GetCategories"
Category="CategoryName"
If you are running the website now the first dropdown should be loaded with data now. If you are getting any errors like error 500 or method error 12031, The chances are the following line might be missed out
<System.Web.Script.Services.ScriptService ()>
It should be along with
<WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Script.Services.ScriptService()> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
After this change hit the run. It should compile and run. If you select the first dropdown it should return the list of categories. If you are not getting any output you may try running the webservice in browser by ‘set as start page’ on the webservice. The logic is make sure the webservice is working as expected and returning the list of categories
For the second drop down the only difference you are going to do is passing a parameter to filter the data based on the parameter. To get the parameter from the selected item of the first DropDownList.
Dim Param As StringDictionary
Param = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Then the Param Dictionary will contain the data we need. We can easily fetch the value from the name value pair like Param("CategoryName") . Use that in the select query to fetch filtered records
Source Code
MarkUp(*.Aspx)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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 id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<cc1:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
ServicePath="NorthwindDataService.asmx" ServiceMethod="GetCategories" Category="CategoryName"
PromptText="Select a Category">
</cc1:CascadingDropDown>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<cc1:CascadingDropDown ID="CascadingDropDown2" runat="server" TargetControlID="DropDownList2"
ServicePath="NorthwindDataService.asmx" ServiceMethod="GetProducts" ParentControlID="DropDownList1"
Category="Products" PromptText="Select a Product">
</cc1:CascadingDropDown>
</form>
</body>
</html>
CodeBehind(*.Aspx.VB)
Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
End Class
Webservice(*.VB)
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports AjaxControlToolkit
Imports System.Data
Imports System.Data.SqlClient
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Script.Services.ScriptService()> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class NorthwindDataService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetCategories(ByVal knownCategoryValues As String, _
ByVal category As String) As CascadingDropDownNameValue()
Dim SelectQry = "select * from Categories"
Dim SampleSource As New List(Of CascadingDropDownNameValue)
Try
Using Command As New SqlCommand(SelectQry, Connection)
Using Reader As SqlDataReader = Command.ExecuteReader()
While Reader.Read
Dim CategoryName = Reader("CategoryName").ToString()
Dim CategoryValue = Reader("CategoryID").ToString()
SampleSource.Add(New CascadingDropDownNameValue( _
CategoryName, CategoryValue))
End While
End Using
Return SampleSource.ToArray()
End Using
Catch ex As Exception
Throw ex
End Try
End Function
<WebMethod()> _
Public Function GetProducts(ByVal knownCategoryValues As String, _
ByVal category As String) As CascadingDropDownNameValue()
Dim Param As StringDictionary
Param = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim SelectQry = "select * from Products where CategoryID = " & Param("CategoryName")
Dim SampleSource As New List(Of CascadingDropDownNameValue)
Try
Using Command As New SqlCommand(SelectQry, Connection)
Using Reader As SqlDataReader = Command.ExecuteReader()
While Reader.Read
Dim CategoryName = Reader("ProductName").ToString()
Dim CategoryValue = Reader("ProductID").ToString()
SampleSource.Add(New CascadingDropDownNameValue( _
CategoryName, CategoryValue))
End While
End Using
Return SampleSource.ToArray()
End Using
Catch ex As Exception
Throw ex
End Try
End Function
Private ReadOnly Property ConnectionString() As String
Get
Return "Server=.\SQLEXPRESS;Database=NorthWind;Trusted_Connection=True"
End Get
End Property
Private ReadOnly Property Connection() As SqlConnection
Get
Dim ConnectionToFetch As New SqlConnection(ConnectionString)
ConnectionToFetch.Open()
Return ConnectionToFetch
End Get
End Property
End Class