通过jquery将项目添加到选择下拉列表中失败 [英] Adding items to a select dropdown via jquery is not succeeding
问题描述
我正在尝试使用ASP.NET MVC中的jquery动态填充下拉列表中的项目.
I am trying to populate items in a drop down list dynamically using jquery in ASP.NET MVC.
这是我的查看代码:
<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";
}
});
}
在MV Controller中,我具有GetLocations
动作方法,如下所示:
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);
}
我在chrome中进行了调试,发现已达到success
,并且还在循环for循环.
但是我无法弄清楚为什么未将这些项添加到下拉菜单中.如果我使用相同的代码向下拉列表中添加了除success
之外的其他项,则将添加这些项.任何帮助将不胜感激.
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.
推荐答案
您可以尝试以下操作:
[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(new SelectList(locations, nameof(SelectListItem.Value), nameof(SelectListItem.Text)););
}
这篇关于通过jquery将项目添加到选择下拉列表中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!