【问题标题】:How to create a loop for dynamic dropdownlist in Jquery?如何在 Jquery 中为动态下拉列表创建循环?
【发布时间】:2021-10-11 21:52:56
【问题描述】:

我有显示控制器的 dropdownlist 的 Javascript 代码:

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>');
                        });
                }
            );
        });

下拉列表值是指南字符串 ...

consol.log 显示如下:

我想单独接收这些值并使用它们……怎么办?

【问题讨论】:

  • 我建议编辑控制器,使selector init方法可以在一个http请求中获取2个selector的选项,以提高效率。
  • @Tiny Wang 我不知道是怎么做到的……你能编辑代码吗?

标签: javascript jquery asp.net loops asp.net-core


【解决方案1】:

我无法完全重建您的应用程序,因为我没有您的 json 数据。
我认为您不能像以前那样附加选项。
只需根据您的需要更改 If 语句,这样它就可以工作了。
请发布您的 getJson 回复,以便我尽力帮助您。

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>

【讨论】:

  • 谢谢,我编辑了我的问题并添加了控制器代码
  • 感谢支持 :-)
【解决方案2】:

我在这里写了一个演示来展示我的想法,希望它可以解决您的问题或至少提出一些想法。

我认为您可以在初始化选择器时准备好所有数据,这意味着您可以通过 1 个 http 请求完成初始化任务。并在 select DOM 上添加 onchange 事件。

我的看法,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>

这是我的家庭控制器:

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>();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 2014-09-19
    相关资源
    最近更新 更多