MVC5 和 jQuery:以编程方式将几个项目添加到下拉列表中



我在使用 MVC5 方面很新。我有一个下拉列表,选择后它会触发控制器,控制器返回项目列表。我想将这些项目添加到另一个下拉列表中。

.cshtml

<select class="comboBox" id="urunGrubu">
<option></option>
</select>

脚本

function getCinsItem() {
var value = document.getElementById("urunCinsi").value;
$.ajax({
dataType: "html",
type: "POST",
url: "/Kuyumcu/UrunEkle1",
data: { k: value },
success: function (data) {
var select = document.getElementById("urunGrubu");
for (index in data) {
select.options[select.options.length] = new Option(data[index], index);
}
}       
});
}

从控制器返回的值:

'["14 AYAR","18 AYAR","21 AYAR","22 AYAR","24 AYAR","8 AYAR","HURDA","SADE"]'

这会将列表中的所有字母作为选项添加到下拉列表中。如何捕捉单词而不是字母?

你不需要在选择中<option>,在循环中也不需要指定你想使用的选项,就像这样select.options[select.options.length]

获取数据后,只需将new Option(即元素)追加到 DOM 中的选择元素。

编辑: 由于我们在评论中谈到了,并且您说当数据来自控制器时,它说类型是string,这意味着您没有真正的数组,您只有该数组的字符串表示形式。
那么,你需要什么?a Parse,可能是在迭代之前JSON.parse(data),以避免对每个字符进行迭代。

下面是一个解析示例:。

var data = '["14 AYAR","18 AYAR","21 AYAR","22 AYAR","24 AYAR","8 AYAR","HURDA","SADE"]'
//Above is a string that came from controller
console.log("Type before parse:", typeof data)
var select = document.getElementById("urunGrubu");
data = JSON.parse(data)
console.log("Type after parse:", typeof data) //parsed as an object/array
for (index in data) {
select.append(new Option(data[index], index));
}
<select class="comboBox" id="urunGrubu">
</select>

我不确定我是否正确理解了你的问题。

我觉得您想将数组的每个项目添加为下拉列表的新选项。

如果是这种情况,那么您提供的代码效果很好。 我在这个jsFiddle上重现行为没有问题(注释的行也可以工作)


在您的评论后编辑:您声明将字符串返回到您的 ajax 请求中,这是完全可行的,如 Calvin Nunes 的答案所示。

但是,如果您不想从客户端将字符串解析为数组或 jsonObject,则可以从以下位置更新控制器方法:

public IActionResult UrunEkle1(TypeOfParameter k)
{
//Retrieve the data you have to return
return data;
}

对此:

public JsonResult UrunEkle1(TypeOfParameter k)
{
//Retrieve the data you have to return
return Json(data);
}

从现在开始,您无需解析结果即可将其用作 json 或数组,这在检索一组复杂的数据(例如自定义类列表)时非常有用。您可以通过以下方式使用此列表:

select.options[select.options.length] = new Option(data[index].label, data[index].id, data[index].isDefaultSelected, data[index].isSelected);

希望它完成接受的答案!

window.populateDropdown = function() {
var select = document.getElementById("urunGrubu");
for (var index in data) {
select.options[select.options.length] = new Option(data[index], index);
//select.options.add(new Option(data[index], index));
}
}
var data = ["14 AYAR", "18 AYAR", "21 AYAR", "22 AYAR", "24 AYAR", "8 AYAR", "HURDA", "SADE"]
<select class="comboBox" id="urunGrubu">
<option>Default Option</option>
</select>
<button type="button" onclick="populateDropdown()">
Trigger
</button>

当然,第一个标签是完全可选的,并且仅适用于诸如"选择一个选项"之类的说明。

最新更新