Home > Software design >  Why Multiple Cascading Dropdown not working
Why Multiple Cascading Dropdown not working

Time:01-17

I have two cascading dropdown first dropdown shows the list of countries and based on the selection of countries the next dropdown gets populated. The problem is that when I Select Value from DropDown the other dropdown not getting populated


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

What am I doing wrong?Could you plase help

CodePudding user response:

The problem is that when I Select Value from DropDown the other dropdown not getting populated.What am I doing wrong?

Well, in var option = $('<option></option>'); we have text and value to append items in it but you are using option.val(id); which is incorrect. In addition, your way of implementations are also very clumsy. As you are using javascript why don't you fully handle it using javascript.

Here, is the the complte example for you:

Model:

     

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

Controller:

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

        }
       
    }

View:

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

        <div >
            <label >Country</label>
            <div >
                <select  id="ddlCountry"></select><br />
            </div>
        </div>

        <div >
            <label >City</label>
            <div >
                <select  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>
    }

Output:

enter image description here

  • Related