Trying to bind a list of objects to a dropdownlist, after PageLoad.
Step 2 works fine and I get the data.
I'm stuck at step 1 and 3.
sCountry is the id of the dropdownlist.
Assuming step 3 is correct, now what should be done in the 'success' part of step 1.
STEP 1 - JS : //Store data in a global object, so that it can be retrieved multiple times.
-------------
var GlobalObjects = { Countries: null,
GetCountries: function () {
if (GlobalObjects.Countries == null) {
$.ajax({
type: "POST",
url: "default.aspx/CountriesData",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (res) {
//What should be done here
},
failure: function (res) {
alert(res.message);
}
});
}
return GlobalObjects.Countries;
}
};
STEP 2 - CS : //Get the data
--------------
[WebMethod]
public static CountryDAL[] CountriesData()
{
CountryDAL cDAL = new CountryDAL();
DataTable dt = cDAL.getdata();
List<CountryDAL> lst = new List<CountryDAL>();
foreach (DataRow dr in dt.Rows)
{
CountryDAL obj = new CountryDAL();
obj.CountryId = Convert.ToInt32(dr["CountryId"]);
obj.CountryName = Convert.ToString(dr["CountryName"]);
lst.Add(obj);
}
return lst.ToArray();
}
STEP 3 - JS : // Bind records to dropdownlist at page load
--------------
$(document).ready(function () {
//Load Countries
var opt = [];
opt.push("<option value='0'>--Select--</option>");
$(GlobalObjects.GetCountries()).each(function (key, value) {
opt.push("<option value=" + value.CountryId + ">" + value.CountryName + "</option>");
});
$("#sCountry").html(opt.join(''));
});