jquery 为什么多个级联下拉不工作

wgeznvg7  于 2023-01-20  发布在  jQuery
关注(0)|答案(1)|浏览(123)

我有两个级联下拉菜单,第一个下拉菜单显示国家/地区列表,根据选择的国家/地区填充下一个下拉菜单。问题是,当我从下拉菜单中选择值时,其他下拉菜单未填充

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.DropDownListFor(x => x.CountryId, Model.Countries,"SEC",null)
    <br />
    @Html.DropDownListFor(x => x.CityId, Model.Cities, "SEC", null)
    <button>Kaydet</button>
}
<div>
    COUNTRYId:@Model.CountryId
</div>
<div>
    CİTYId:@Model.CityId
</div>
<script>
    
    $('#CountryId').change(function () {
     
                var val = $(this).val();
        if (val != "" || val != -1) {
            $('#CountryId option').not(":first").remove();
         
            $.ajax({
                method: "GET",
                url: '@Url.Action("GetByCountryId","Home")' + "/" + val;
              
            }).done(function (result) {
                for (var i = 0; i < result.length; i++) {
                    var name = result[i].CityName;
                    var id = result[i].CityId;
                    var option = $('<option></option>');
                    option.text(name);
                    option.val(id);
                    $('#CityId').append(option);
                }
            })

        } else {
            $('#CountryId option').not(":first").remove();
        }

    })
     
    
</script>
public JsonResult GetByCountryId(int id)
        {
            var cities = Cities.GetFakeCities().Where(x => x.CountryId == id).ToList();
            return Json(cities, JsonRequestBehavior.AllowGet);
        }

我做错什么了?你能帮我吗

yduiuuwa

yduiuuwa1#

问题是当我从下拉列表中选择值时,其他下拉列表没有被填充。我做错了什么?
好吧,在var option = $('<option></option>');中我们有textvalue来添加项目,但是你用的是option.val(id);,这是不正确的。另外,你的实现方式也很笨拙。既然你用的是javascript,为什么不完全用javascript来处理呢?
下面是一个完整的示例:
型号:

public class Country
    {
        public int CountryId { get; set; }
        public string? CountryName { get; set; }
    }
      
public class City
    {
        public int CityId { get; set; }
        public string CityName { get; set; }
        public int CountryId { get; set; }
    }

控制器:

public class CascadingDropdownController : Controller
    {
       
        public static List<Country> ListOfCountry = new List<Country>()
        {
            new Country() { CountryId =101, CountryName ="INDIA", },
            new Country() { CountryId =102, CountryName ="USA", },
            new Country() { CountryId =103, CountryName ="UK", },
            new Country() { CountryId =104, CountryName ="Canada", },
        };

       

        public static List<City> ListOfCity = new List<City>()
        {
            //INDIA
            new City() { CountryId =101, CityId =1, CityName = "Delhi" },
            new City() { CountryId =101, CityId =2, CityName = "Haydrabad" },
            new City() { CountryId =101, CityId =3, CityName = "Pune" },
            //USA
            new City() { CountryId =102, CityId =4, CityName = "New York" },
            new City() { CountryId =102, CityId =5, CityName = "Silicon Valley" },
            new City() { CountryId =102, CityId =6, CityName = "Dallaus" },
            //UK
            new City() { CountryId =103, CityId =7, CityName = "London" },
            new City() { CountryId =103, CityId =8, CityName = "Cardif" },
            new City() { CountryId =103, CityId =9, CityName = "Sundarland" },
             //Candada
            new City() { CountryId =104, CityId =10, CityName = "Alberta" },
            new City() { CountryId =104, CityId =11, CityName = "Ontario" },
            new City() { CountryId =104, CityId =12, CityName = "Manitoba" },
        };
       

       
        public IActionResult Index()
        {
            return View();
        }
       
       
        [HttpGet]
        public async Task<ActionResult> LoadCountry()
        {
            var country = ListOfCountry.ToList();
           
            return Ok(country);
           
        }

       
        [HttpGet]
        public async Task<ActionResult> GetCity(int countryId)
        {
            var citys = ListOfCity.Where(cId => cId.CountryId == countryId).ToList();

            return Ok(citys);

        }
       
    }

查看:

<div class="row">
    <div class="col-lg-3"></div>
    <div class="col-lg-6">

        <div class="form-group">
            <label class="col-md-4 control-label">Country</label>
            <div class="col-md-6">
                <select class="form-control" id="ddlCountry"></select><br />
            </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">City</label>
            <div class="col-md-6">
                <select class="form-control" id="ddlCity"></select>
                <br />

            </div>
        </div>
        <br />
    </div>
    </div>


    @section scripts {
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
        <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
        <script>

            $(document).ready(function () {

                var ddlCountry = $('#ddlCountry');              
                ddlCountry.append($("<option></option>").val('').html('Please Select Country'));

                var ddlCity = $('#ddlCity');
                ddlCity.append($("<option></option>").val('').html('Please Select Country First'));

                $.ajax({
                    url: 'http://localhost:5094/CascadingDropdown/LoadCountry',
                    type: 'GET',
                    dataType: 'json',
                    success: function (d) {
                        console.log(d);
                        $.each(d, function (i, country) {
                            console.log(i);
                            console.log(country);

                            ddlCountry.append($("<option></option>").val(country.countryId).html(country.countryName));
                        });
                    },
                    error: function () {
                        alert('Error!');
                    }
                });

                //City details by country id

                $("#ddlCountry").change(function () {

                    //alert("On ddlCountry change");
                    var CountryId = parseInt($(this).val());
                    console.log(CountryId);
                    if (!isNaN(CountryId)) {
                        var ddlCity = $('#ddlCity');
                        ddlCity.empty();
                        ddlCity.append($("<option></option>").val('').html('Please wait ...'));

                        $.ajax({
                            url: 'http://localhost:5094/CascadingDropdown/GetCity',
                            type: 'GET',
                            dataType: 'json',
                            data: { CountryId: CountryId },
                            success: function (d) {

                                ddlCity.empty(); // Clear the please wait
                                ddlCity.append($("<option></option>").val('').html('Select City'));
                                $.each(d, function (i, citys) {
                                    ddlCity.append($("<option></option>").val(citys.cityId).html(citys.cityName));
                                });
                            },
                            error: function () {
                                alert('Error!');
                            }
                        });
                    }

                });

            });
        </script>
    }

输出:

相关问题