I am trying to populate items in a drop down list dynamically using jquery in ASP.NET MVC.
This is my view code :
<select id="StartLocation" class="custom-select", onchange = "highlightMarkerById(this.value,0)">
<option value="">-Start Location-</option>
</select>
This is the function I call to get the data :
function GetLocations() {
$.ajax({
type: "POST",
url: "/MV/GetLocations",
dataType: "json",
success: function (data) {
for (var j = 0; j < data.length ; j++) {
$('#StartLocation').append($('<option>', {
value: data[j].Value,
text: data[j].Text
}));
}
},
error: function () {
return "error";
}
});
}
In MV Controller, I have the GetLocations
action method as follows :
[HttpPost]
public JsonResult GetLocations()
{
List<vlocation> locationslist = DBManager.Instance.GetLocations();
List<SelectListItem> locations = new List<SelectListItem>();
foreach(var loc in locationslist)
{
locations.Add(new SelectListItem { Value = loc.displayName, Text = loc.displayName });
}
return Json(locations);
}
I debugged in chrome and found that the success
is reached and the for loop is also being iterated.
But I can't figure out why the items are not being added to the drop down. If I use the same code to add some items to the drop down other than inside the success
, the items are being added. Any help would be appreciated.