Building Cascading DropDownList in ASP.Net Using jQuery and JSON
时间:2010-08-12 来源:yuzhangqi
Cascading DropDownList is a technique where we populate a child DropDownList based on the parent DropDownList selection. It is often used in web applications. In this blog I will show you how to implement a cascading dropdownlist using jQuery and Json in ASP.Net.
Let's begin with a real example.
As shown in pictures above, when we select a Building in Home Building DropDownList, it will populate the HomeRoom DropDownList based on the HomeBuilding selected.
Now let's take a look at the key points.
1. Define the data format for Json data. It looks as below:
[{"SpaceName":"1-S","ID":"2101"},{"SpaceName":"1608-A","ID":"2886"}]
JSON format is simply key- value pairs, separated by commas and enclosed in curly braces. Thus, each city is enclosed in curly braces. The key and value can be enclosed by single quote(') or double quote(").
2. Construct an HttpHandler which can accept the HomeBuildingID and give back the list of Home Rooms available in that Home Building in JSON format.
To do this, Right click the project in solution within from Visual Studio 2008 and click “Add New Item”. Select “Generic Hanlder”. I have named it as LoadSpaceRoomHandler.ashx. Here is a code piece:
Public Class LoadSpaceRoomHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim BuildingID As String = context.Request.QueryString("BuildingID")
Dim sbHomeRoom As StringBuilder = New StringBuilder()
sbHomeRoom.Append("[")
For Each item In m_objHomeRooms
sbHomeRoom.Append("{")
sbHomeRoom.Append(DoubleQuote & "SpaceName" & DoubleQuote)
sbHomeRoom.Append(":")
sbHomeRoom.Append(DoubleQuote & item.SpaceName.ToString().Replace(DoubleQuote, String.Empty) & DoubleQuote)
sbHomeRoom.Append(Comma)
sbHomeRoom.Append(DoubleQuote & "ID" & DoubleQuote)
sbHomeRoom.Append(":")
sbHomeRoom.Append(DoubleQuote & item.ID.ToString() & DoubleQuote)
sbHomeRoom.Append("}")
sbHomeRoom.Append(Comma)
Next
sbHomeRoom.Remove(sbHomeRoom.Length - 1, 1)
sbHomeRoom.Append("]")
Try
context.Response.ContentType = "application/json"
context.Response.ContentEncoding = Encoding.UTF8
context.Response.Write(sbHomeRoom.ToString())
context.Response.End()
Catch ex As Exception
End Try
End Sub
End Class
3. Calling HttpHanlder from jQuery
<script language="javascript" type="text/javascript" src="../js/jQuery/jquery.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(documentReady);
function documentReady() {
$("[id$='_HomeBuildingDropDownList']").change(HomeBuildingDropDownList_Change);
}
function HomeBuildingDropDownList_Change() {
$("[id$='_HomeRoomDropDownList']").html("");
var BuildingID = $("[id$='_HomeBuildingDropDownList']").val();
if (BuildingID != "") {
$.getJSON('LoadSpaceRoomHandler.ashx?BuildingID=' + BuildingID, function(HomeRooms) {
$.each(HomeRooms, function() {
$("[id$='_HomeRoomDropDownList']").append($("<option></option>").val(this['ID']).html(this['SpaceName']));
});
});
}
</script>
4. Optimize jQuery.Each() performance
In my real application, there are more than 1600 data items loading in HomeRoom Dropdownlist. $.each() method make it render the dropdownlist very slowly. To improve performance here, I populate all dropdownlist data items into html instead iterate the data item array. The code optimzed like below:
in HttpHandler:
sbHomeRoom.Append("[")
sbHomeRoom.Append("{")
sbHomeRoom.Append(DoubleQuote + "content" + DoubleQuote)
sbHomeRoom.Append(":")
sbHomeRoom.Append(DoubleQuote)
For Each item In m_objHomeRooms
sbHomeRoom.Append("<option " + "value=" + item.ID.ToString() + ">")
sbHomeRoom.Append(item.SpaceName.ToString().Replace(DoubleQuote, String.Empty))
sbHomeRoom.Append("</option>")
Next
sbHomeRoom.Append(DoubleQuote)
sbHomeRoom.Append("}")
sbHomeRoom.Append("]")
in ASPX page:
function HomeBuildingDropDownList_Change() {
$("[id$='_HomeRoomDropDownList']").html("");
var BuildingID = $("[id$='_HomeBuildingDropDownList']").val();
if (BuildingID != "") {
$.getJSON('LoadSpaceRoomHandler.ashx?BuildingID=' + BuildingID, function(HomeRooms) {
$("[id$='_HomeRoomDropDownList']").append(HomeRooms[0]['content']);
});
}
}
This time the cascading dropdownlist rendered quickly.