Saturday, August 15, 2009

Populate dropdown based on selection of other dropdown in ASP.NET Using Jquery Json

I have used the Json technique to retrieve the server side records on the client side in my post Using Json in Asp.net Application, where I have explain how you can retrieve json data. Now here in this post i will use same example which is used in that post and show you how you can use the json of the jquery.For detail of the example you can visit my Using Json in Asp.net Application,post , here I will explain the JavaScript I have used to retrieve the values of the second dropdown list control. Here is my JavaScript code. In the code below I just bind the change event to the ddlRegion dropdown list control which also act as parent control. In the change event of the region dropdown list control, I have save the value of the region which is the id of the region and then build the url which consist of the page name plus the regionID and the sid as query string parameters.
$(document).ready(function()
{
$("#ddlRegion").change(function(){
var regionID = this.value;

var url="ResponsePage.aspx";
url=url+"?regionID="+ regionID;
url=url+"&sid="+Math.random();

$.getJSON(url, function(returnDataCollection)
{
$("#ddlTerritory")[0].innerHTML ='';
for(var intCounter=0; intCounter < returnDataCollection.length-1; intCounter++)
{
$("#ddlTerritory").append($("<option></option>").val(returnDataCollection[intCounter].TerritoryID ).html(returnDataCollection[intCounter].TerritoryDescription));
}
});
});
});

Next is the call to the $.getJSON function and here is the syntax of the $.getJSON function.
 $.getJSON(url[, data][, success]) 
Here are the detail of the parameter list which are passed to the function.
  • url: A string containing the URL to which the request is sent
  • data: (optional): A map of data that is sent with the request
  • success: (optional): A function that is executed if the request succeeds
And $.getJSON function return the XMLHttpRequest object that was created.The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the eval() function. Then in the success function I have loop through the array collection and add the values in the next dropdownlist control.You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

No comments: