C# 如何使用单个ajax调用填充多个dropdownList
下面的代码生成5个下拉列表C# 如何使用单个ajax调用填充多个dropdownList,c#,jquery,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 =
@{
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> </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.onchange,函数事件{
$.ajax{
类型:post,,
url:/Question/GetQuestions,
数据:{TypeId:$'ReflectionType'.val},
数据类型:json,
传统的:是的,
成功:函数数据{
调试器;
$.eachdata,函数索引,值{
var标记=;
$Question.append+value.Question+;
};
}
};
这将生成如下问题0、问题1、问题2、问题3、问题4的唯一id
$("#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>');
})
希望这能解决您的问题。祝您编码愉快!为什么对所有5个下拉列表保留相同的id问题?根据定义,id在页面中必须是唯一的…使用类instead@RahulRaut在这种情况下,当在for循环中创建下拉列表时,如何拥有唯一的ID?新建{@class=form-control,@id=Question+i,@style=width:900px;}这就是生成唯一id的方法。
$('[id^=Question]').each(function(index,element){
$(element).append('<option value="' + value.Question + '">' + value.Question + '</option>');
})