How to create a loop for dynamic dropdownlist in Jquery?

Viewed 441

I have Javascript code that display dropdownlist from controller :

public async Task<IActionResult> GetSubCategory(Guid id)
    {
        var SubCategory_List = await _admin.GetGategories();

        return Json(new SelectList(SubCategory_List.Where(c => c.ParentId == id), "Id", "CategoryName"));

    }
  





$.getJSON("/AdminPanel/Product/GetFirstSub/" + np.MainCat,
function (data) {
    $.each(data,
        function () {
            $("#firstsub").append('<option value= ' + this.value + '>' + this.text + '</option>');

            const idfirst = this.value;
            console.log(idfirst);                           

            $("#CategoryId").empty();
            $.getJSON("/AdminPanel/Product/GetSecondSub/" + idfirst,
                function (data) {
                    $.each(data,
                        function () {
                            $("#CategoryId").append('<option value= ' + this.value + '>' + this.text + '</option>');
                        });
                }
            );
        });

dropdownlist values are Guide string ...

consol.log display this:

enter image description here

I want to receive these values ​​individually and use them ... How can do this?

2 Answers

I can not rebuild your application exactly because I don't have your json data.
I don't think you can append options like you did it.
Just change the If statement to your needs so it should work.
Please post your getJson response so I try to help you.

var getEmployeeDataFromJson = new Promise(
  function(resolve) {
    $.getJSON("https://raw.githubusercontent.com/bmehler/employees/main/employees", function(data) {
      resolve(data);
    });
  }
);

var getProductDataFromJson = new Promise(
  function(resolve) {
    $.getJSON("https://raw.githubusercontent.com/bmehler/product/main/product.json", function(data) {
      resolve(data);
    });
  }
);

getEmployeeDataFromJson
  .then(function(data_employee) {
    console.log('data-employee', data_employee);
    $.each(data_employee, function(index, value) {
      $('#firstsub').append($('<option>', {
        value: value.id,
        text: value.name
      }));
    });
    getProductDataFromJson
      .then(function(data_product) {
        console.log('data-product', data_product);
        $.each(data_product, function(index, value) {
        // Change this to your needs
          if (value.category == 'Electronics') { // == data_employee[0].id
            $('#CategoryId').append($('<option>', {
              value: value.category,
              text: value.name
            }));
          }
        });
      })
      .catch(function(error) {
        console.log(error.message);
      });

  })
  .catch(function(error) {
    console.log(error.message);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="firstsub">
</select>
<select id="CategoryId">
</select>

I write a demo to show my idea here, hope it could solve your problem or come up with some ideas at least.

I think you can prepare all the data when initialize selectors, that means you can finish the init task via 1 http request. And add onchange event on the select DOM.

My view, home.cshtml

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div>
    <select id="city"></select>
    <select id="town"></select>
</div>

<script>
    $(function () {
        initSel();
    });

    $("#city").change(function () {
        var cityid = $("#city option:checked").val();
        console.log(cityid);
        $.ajax({
            url: "https://localhost:44319/home/getTownsById",
            data: {
                cityId: cityid
            },
            success: function (data) {
                console.info("towns:" + data);
                $("#town").html("");
                for (var i = 0; i < data.length; i++) {
                    $("#town").append('<option value= ' + data[i].townId + '>' + data[i].townName + '</option>');
                }
            }
        });
    });

    function initSel() {
        $.ajax({
            url: "https://localhost:44319/home/init",
            dataType:"json",
            success: function (data) {
                console.info(data);
                for (var i = 0; i < data.cities.length; i++) {
                    $("#city").append('<option value= ' + data.cities[i].cityId + '>' + data.cities[i].cityName + '</option>');
                }
                for (var i = 0; i < data.towns.length; i++) {
                    $("#town").append('<option value= ' + data.towns[i].townId + '>' + data.towns[i].townName + '</option>');
                }
            }
        });
    }
</script>

And this is my home controller:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public JsonResult init() {
            List<City> cities = new List<City>
            {
                new City{ CityId="city1", CityName="city1"},
                new City{ CityId="city2", CityName="city2"},
                new City{ CityId="city3", CityName="city3"}
            };
            var firstCityId = cities[0].CityId;
            var towns = getTownsById(firstCityId);
            Dictionary<string, object> res = new Dictionary<string, object>();
            res.Add("cities", cities);
            res.Add("towns", towns);
            return Json(res);
        }

        public List<Town> getTownsById(string cityId) {
            List<Town> data = new List<Town>
            {
                new Town{ CityId="city1",TownId="town1", TownName="town1"},
                new Town{ CityId="city1",TownId="town2", TownName="town2"},
                new Town{ CityId="city2", TownId="town3", TownName="town3"},
                new Town{ CityId="city2", TownId="town4", TownName="town4"},
                new Town{ CityId="city3", TownId="town5", TownName="town5"}
            };
            var towns = data.AsQueryable().Where(town => town.CityId == cityId);
            return towns.ToList<Town>();
        }
    }
}
Related