如何使用单个Ajax调用填充多个dropdownList

时间:2019-04-01 03:26:49

标签: c# jquery

下面的代码生成5个下拉列表。

@{
for (int i = 0; i < 5; i++) { <tr>
    <td> @Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { @class = "form-control ", @type = "text",
        @placeholder = " QNo", @required = "", @id = "txtQNo", @style = "width:60px;" } }) </td>
    <td>&nbsp;&nbsp;&nbsp;</td>
    <td> @Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty, "Value", "Text"), "Select Question",
        new { @class = "form-control ", @id = "Question", @style = "width:900px;" })</td>

    </tr>
    }
  }

我正在尝试使用下面的ajax调用接收到的一堆值填充上面的5个下拉菜单

$("#ReflectionType").on("change", function (event) {
    $.ajax({
        type: "post",
        url: "/Question/GetQuestions",
        data: { TypeId: $('#ReflectionType').val() },
        datatype: "json",
        traditional: true,
        success: function (data) {
            debugger;
            $.each(data, function (index, value) {

                var markup = '';
                $("#Question").append('<option value="' + value.Question + '">' + value.Question + '</option>');
               
            });
           
        }
    });

上面的代码段仅更新了一个下拉列表(第一个下拉菜单),在该列表中应该更新所有五个下拉列表。

1 个答案:

答案 0 :(得分:1)

@{
for (int i = 0; i < 5; i++) { <tr>
    <td> @Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { @class = "form-control ", @type = "text",
    @placeholder = " QNo", @required = "", @id = "txtQNo", @style = "width:60px;" } })</td>
    <td>&nbsp;&nbsp;&nbsp;</td>
    <td> @Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty,"Value", "Text"), "Select Question",
    new { @class = "form-control ", @id = "Question"+i, @style = "width:900px;" })</td>

</tr>
   }
}

这将生成唯一的ID,如下问题0,问题1,问题2,问题3,问题4

$("#ReflectionType").on("change", function (event) {
$.ajax({
    type: "post",
    url: "/Question/GetQuestions",
    data: { TypeId: $('#ReflectionType').val() },
    datatype: "json",
    traditional: true,
    success: function (data) {
        debugger;
        $.each(data, function (index, value) {

            var markup = '';
            for(let j = 0; j < 5; j++){
                $("#Question"+j).append('<option value="' + value.Question + '">' + value.Question + '</option>');
           }
        });

    }
});

正如我所见,您的循环正在运行5次迭代,您可以用相同的方式运行它,并从ajax调用中追加数据。或者您可以按如下方式使用带选择器的开始

$('[id^=Question]').each(function(index,element){
 $(element).append('<option value="' + value.Question + '">' + value.Question + '</option>');
})

希望这可以解决您的问题。祝您编码愉快!