使用 jquery 或 JS 填充 Html.DropDownList [英] Populate Html.DropDownList with jquery or JS

查看:22
本文介绍了使用 jquery 或 JS 填充 Html.DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我所拥有的:

for (i = 0; i ').attr('value', data[i].id).attr('name', data[i].name));}

但下拉列表始终保持不变.为什么这不起作用?数据变量具有漂亮的值.另外,我想在 for 循环之前清空下拉列表/如何做?

这是我在视图中的下拉列表:

<%= Html.DropDownList("myDropDownLisTId")%>

解决方案

试试这个.

$.each(data, function() {$("#myDropDownLisTId").append($("<option/>").val(this.id).text(this.Text));});

查看我的这个答案,了解有关如何从 MVC 操作获取数据以加载下拉列表的更多详细信息>

根据删除现有数据的评论

$("#myDropDownLisTId").empty()$.each(data, function() {$("#myDropDownLisTId").append($("<option/>").val(this.id).text(this.Text));});

编辑 2:Idrumsgood 的回答有一个很好的观点.无需每次在循环内调用 append 方法,只需将值保存在变量中,并且只调用一次 html 方法.

http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

var items=""$.each(数据,函数(){items+="

Here is what I have:

for (i = 0; i < data.length; i++) {
                $("#myDropDownLisTId").find('tbody')  
                .append($('<option>').attr('value', data[i].id).attr('name', data[i].name)
                );               
            }

But the dropdown list always remains the same. Why is this not working? the data variable has beautiful values. Also, I would like before the for loop to empty the dropdown list/ How to do it?

Here is my drop down list in the view:

<%= Html.DropDownList("myDropDownLisTId")%>

解决方案

Try this.

$.each(data, function() {
   $("#myDropDownLisTId").append($("<option />").val(this.id).text(this.Text));
 });

Check my this answer for more details about how to get data from an MVC action to load the dropdown list

EDIT: As per the comment to remove existing data

$("#myDropDownLisTId").empty()
$.each(data, function() {
   $("#myDropDownLisTId").append($("<option />").val(this.id).text(this.Text));
 });

EDIT 2:  Idrumsgood's answer has a very good point. Instead of calling the append method everytime inside the loop, just keep the value inside a variable and call the html method only once.

http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

var items=""
$.each(data, function() {
   items+="<option value='" + this.id + "'>" + this.Text + "</option>";
 });
$("#myDropDownLisTId").html(items);

这篇关于使用 jquery 或 JS 填充 Html.DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆