We’re working on a big ASP.NET\VB.NET website project.
I need to populate three dropdownlists. To last two are independent of the previous ones. The population data comes from an SQL Server. I’d have no problem doing this with code-behind with post back but we don’t want any PostBacks so I started to develop this in Ajax\jQuery.
Preface:
The dropdownlist’s values and text are both different and tied up to the database. Server-side, the function called by the Ajax method returns a list of list of string with the values and text, i.e.
list[0][0] = "ID0"
list[0][1] = "VP"
The list is well built and returns the right value taken from the database.
Problem:
Now I want to populate the dropdownlist from the list sent to the ajax success response and I have a hard time doing it.
Here’s the ajax part of it so far
$.ajax(
{
type: "POST",
url: "Projet.aspx/GetDir",
data: "{VP:'" + dd_effort_vp + "',DP:'" + dd_effort_dp + "',Direction:'" + dd_effort_d + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
// This code works if only a simple list of string is
// returned from the server-side called function.
var cars = response.d;
$.each(cars, function(index, value) {
$('#<%= dd_effort_directionp.clientid()%>').append(
$('<option></option>').val(value).html(value));
});
}
This code works IF and only IF I have a simple list of string returned by the server side function.
Now I want to modify it to get the values from the List of List of String (in var cars and assign the right ID and Description to each item in the newly populated DropdownList.
If your server is returning to you a list of list of strings, that will come to jQuery via an array, whose elements are arrays. You need to figure out/know which element of that array—which, again, will contain a list of strings—needs to go with your dropdown. If you want the 0th array, you would do:
Also, it looks like you’re going through a lot of trouble to find the relevant dropdown lists since asp.net is giving them unpredictable names.
Consider giving each drop down a unique class, via the CssClass property, and then select it that way.