0

How can you fill a DropDownList using jQuery?

I have a call to my controller :

$.getJSON('@Url.Action("GetCategories")', { groupId: selectedGroup }, function (categories) {

This returns objects from the class Category :

  public class Category
  {
      public int Id { get; set; }
      public int GroupId { get; set; }
      public string Description { get; set; }
  }

How do I get the Id from Category in the DropDownList value and Description from Category in the Text?

This is not working..

$.each(categories, function (index, category) {
categoriesSelect.append($('<option/>', {
    value: category.Id,
    text: category.Description
 }));
});

This is not working, it gives the message "category not defined".

This is what is in category:

enter image description here

user7849697
  • 503
  • 1
  • 8
  • 19
  • Debug. Set a breakpoint and see what's actually in `categories`. Or use `console.log(JSON.stringify(categories, null, 2))` and see what's actually coming back from your service. – Heretic Monkey Nov 07 '19 at 21:05
  • @HereticMonkey updated my question with a debug screenshot – user7849697 Nov 07 '19 at 21:08

4 Answers4

0

Here you go:

categoriesSelect.append($("<option></option>")
    .attr("value", category.Id)
    .text(category.Description));
0

I made a little mistake, it should be category.id instead of category.Id and category.description instead of category.Description.

user7849697
  • 503
  • 1
  • 8
  • 19
  • Does this answer your question then? You've written it as an answer, but it doesn't seem to answer why you were getting a message about category not being defined... – Heretic Monkey Nov 07 '19 at 21:20
  • No idea but this seems to work, the message was because I didn't push f11 to continue I guess. – user7849697 Nov 07 '19 at 21:22
0

I notice in your question, that the table of categories that you receive in ajax are objects:

 public class Category
  {
      public int Id { get; set; }
      public int GroupId { get; set; }
      public string Description { get; set; }
  }

your attributes in the answer ajax change Id -> id; GroupId -> groupId; Description -> description. it seems like there is a conversion from your first attribute letter to lowercase. Please take it into account when you build your drop-down list

This code could do the trick. The category array here contains objects in the format of the response that you receive called the call 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>
akoo yvan
  • 1
  • 2
  • This answer can also help you :https://stackoverflow.com/questions/740195/adding-options-to-a-select-using-jquery?answertab=votes#tab-top – akoo yvan Nov 09 '19 at 10:06
-1

Try doing like this,

$.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));
            });
        }
    }
}); 
Mahmoud Sayed
  • 151
  • 2
  • 10