如何使用jQuery填充DropDownList?
我正在打电话给我的控制器:
$.getJSON('@Url.Action("GetCategories")', { groupId: selectedGroup }, function (categories) {
这将从类Category中返回对象:
public class Category
{
public int Id { get; set; }
public int GroupId { get; set; }
public string Description { get; set; }
}
如何从DropDownList值中的类别中获取ID和从文本中的类别中获取描述?
这不起作用..
$.each(categories, function (index, category) {
categoriesSelect.append($('<option/>', {
value: category.Id,
text: category.Description
}));
});
这不起作用,它显示消息“未定义类别”。
这是类别:
categoriesSelect.append($("<option></option>")
.attr("value", category.Id)
.text(category.Description));
public class Category
{
public int Id { get; set; }
public int GroupId { get; set; }
public string Description { get; set; }
}
您在答案ajax中的属性更改Id -> id
;GroupId -> groupId
;Description -> description
。似乎您的第一个属性字母转换为小写字母。构建下拉列表时,请考虑到这一点此代码可以解决问题。这里的category数组包含您收到的响应格式的对象,称为调用Ajax:
$(function(){ // soit ce tableau de catéogies. Dans ton cas, tu la reçoi après ton appel AJAX var categories = [ { id: 1, groupId: "Gp1", description: "Category 1" }, { id: 2, groupId: "Gp1", description: "Category 2" }, { id: 3, groupId: "Gp1", description: "Category 3" }, { id: 4, groupId: "Gp1", description: "Category 4" }, { id: 5, groupId: "Gp1", description: "Category 5" }]; // Vide au préalable la liste déroulante sinon, la liste de catégories renvoyées en Ajax viendra s'ajouter à celles déja charger $("#myDynamicSelect").html(""); // Avec une boucle, tu parcours ton table de catégories "categories", dans ton cas tu la reçoi dans ta réponse ajax $.each(categories, function(i, category){ // Pour chaque catégorie, tu l'insère dans la liste déroulante. Veille bien à renseigner le bon attribut id de ta liste déroule. ici "#myDynamicSelect" var option = new Option( category.description, category.id); $("#myDynamicSelect").append(option); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="myDynamicSelect"></select>
$.get('http://webapi.com' , function (res) {
if (res)
{
if (res.customers && res.customers.length > 0)
{
$.each(res.customers, function (id, cus) {
$("#customers-dropdown").append($('<option></option>').val(cus.id).html(cus.name));
});
}
}
});