Eliza Eliza - 5 months ago 26
jQuery Question

Getting value from a dropdown list that was populated with AJAX

I had populated an ASP.net dropdown list with AJAX now I need to get the Id to store in into the database in a C# method, (I'm using LINQ)

This is my webmethod

[WebMethod]
public static ArrayList GetLanguageList()
{
ArrayList lstArrLanguage = new ArrayList();
IQueryable<Common.Town> myList = new SupplierBL().GetTowns();
foreach(Common.Town t in myList)
{
string name = t.Name;
string id = t.TownId.ToString();
lstArrLanguage.Add(new ListItem(name, id));
}

return lstArrLanguage;
}


My test.aspx code

<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "test.aspx/GetLanguageList",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#ddlLanguage").empty().append($("<option></option>").val("[-]").html("Please select"));
$.each(msg.d, function () {
$('#<%=ddlLanguage.ClientID%>').append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("An error has occurred during processing your request.");
}
});
});
</script>

Answer

You can't get selected value from DropDownList if you adding options in javaScript. You can try the following

string selectedValue = Request.Form[ddlLanguage.UniqueID];

This question may be useful also.