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

下面的代码生成 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>');

               

            });

           

        }

    });


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


哆啦的时光机
浏览 100回答 1
1回答

函数式编程

@{for (int i = 0; i < 5; i++) { <tr>&nbsp; &nbsp; <td> @Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { @class = "form-control ", @type = "text",&nbsp; &nbsp; @placeholder = " QNo", @required = "", @id = "txtQNo", @style = "width:60px;" } })</td>&nbsp; &nbsp; <td>&nbsp;&nbsp;&nbsp;</td>&nbsp; &nbsp; <td> @Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty,"Value", "Text"), "Select Question",&nbsp; &nbsp; new { @class = "form-control ", @id = "Question"+i, @style = "width:900px;" })</td></tr>&nbsp; &nbsp;}}这将生成唯一的 id,如下所示 Question0、Question1、Question2、Question3、Question4$("#ReflectionType").on("change", function (event) {$.ajax({&nbsp; &nbsp; type: "post",&nbsp; &nbsp; url: "/Question/GetQuestions",&nbsp; &nbsp; data: { TypeId: $('#ReflectionType').val() },&nbsp; &nbsp; datatype: "json",&nbsp; &nbsp; traditional: true,&nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; debugger;&nbsp; &nbsp; &nbsp; &nbsp; $.each(data, function (index, value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var markup = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(let j = 0; j < 5; j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#Question"+j).append('<option value="' + value.Question + '">' + value.Question + '</option>');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }});如我所见,您的循环正在运行 5 次迭代,您可以以相同的方式运行它并附加来自 ajax 调用的数据。或者您可以使用 starts with selector 如下$('[id^=Question]').each(function(index,element){&nbsp;$(element).append('<option value="' + value.Question + '">' + value.Question + '</option>');})希望这能解决您的问题。快乐编码!
打开App,查看更多内容
随时随地看视频慕课网APP