如何迭代SelectListItem';使用JavaScript/jQuery进行测试?
服务器端:我将ViewBag设置为“IEnumerable”类型 Cliectside:迭代ViewBag以生成下拉列表 如何使用JavaScript/jQuery迭代SelectListItems Firefox错误消息:“TypeError:list.each不是一个函数”如何迭代SelectListItem';使用JavaScript/jQuery进行测试?,javascript,jquery,loops,razor,selectlistitem,Javascript,Jquery,Loops,Razor,Selectlistitem,服务器端:我将ViewBag设置为“IEnumerable”类型 Cliectside:迭代ViewBag以生成下拉列表 如何使用JavaScript/jQuery迭代SelectListItems Firefox错误消息:“TypeError:list.each不是一个函数” 功能测试(){ var modtagerId=$(“#modtagerId”); modtagerId.empty(); //ViewBag.dropdownModtagerListeNyhedsbrev的类型为“IEn
功能测试(){
var modtagerId=$(“#modtagerId”);
modtagerId.empty();
//ViewBag.dropdownModtagerListeNyhedsbrev的类型为“IEnumerable”
var list=ViewBag.dropdownModtagerListeNyhedsbrev;
列表。每个(函数(){
$("", {
瓦尔:这个值,
text:this.text
}).附录(modtagerId);
});
}
我终于解决了这个问题。我改用JavaScriptforeach
,并使用
逃离剃刀
如果有人关心,我的解决方案是:(我为其他人保留console.log()
函数updateModtagerGruppeDropdown(){
var modtagerId=$(“#modtagerId”);
modtagerId.empty();
@foreach(ViewBag.dropdownModtagerListeVelkomstbrev中的var项)
{
@:console.log('list:'+“@(item.Value)”+,“+”@(item.Text)”);
var value=“@(项目值)”;
var text=“@(Html.Raw(item.text))”;
$("", {
瓦尔:价值,
文本:文本
}).附录(modtagerId);
}
}
。每个都是jquery方法,列表是jquery对象吗?否,//ViewBag.dropdownModtagerListeNyhedsbrev属于“IEnumerable”类型,所以我应该(以某种方式)将其设置为jquery对象吗?或者专注于迭代我准备好的对象。这里应该有一个我错过的最佳实践。
function test() {
var modtagerId = $('#ModtagerId');
modtagerId.empty();
// ViewBag.dropdownModtagerListeNyhedsbrev is of type "IEnumerable<SelectListItem>"
var list = ViewBag.dropdownModtagerListeNyhedsbrev;
list.each(function () {
$("<option />", {
val: this.value,
text: this.text
}).appendTo(modtagerId);
});
}
function updateModtagerGruppeDropdown() {
var modtagerId = $('#ModtagerId');
modtagerId.empty();
@foreach (var item in ViewBag.dropdownModtagerListeVelkomstbrev)
{
@:console.log('list: ' + "@(item.Value)" + ", " + "@(item.Text)");
<text>
var value = "@(item.Value)";
var text = "@(Html.Raw(item.Text))";
$("<option />", {
val: value,
text: text
}).appendTo(modtagerId);
</text>
}
}