Home > Enterprise >  Cascading Dropdown list in .NET 6 MVC getting 404 error
Cascading Dropdown list in .NET 6 MVC getting 404 error

Time:07-30

I am trying to build a cascading dropdown list with a list of countries mapped with their corresponding states. The data is being accessed from SQL Server. I am able to build the country list using the db. However, I am unable to see the data for the states.

CountryStateService.cs:

public async Task<IEnumerable<StateModel>> GetStates(int countryId) {
    var data = await (from cs in db.CountryStates
                      where cs.IdCid == countryId
                      select new StateModel 
                      {
                        stateId = cs.stateId,
                        stateName = cs.stateName,
                        IdCid = cs.IdCid
                      }).ToListAsync();

    return data;
}

Home Controller:

[HttpGet]
public async Task<IActionResult> LoadStateForCountry(int countryId) {
    var stateCollection = await _service.GetStates(countryId);
    List<StateModel> stateList = stateCollection.ToList();

    ViewBag.StateList = stateList;
    return View();
}

JQuery: [This is likely the problem as I am unable to see the data.]

<script type="text/javascript">
    $(document).ready(function() { 
        $('#countryDropDown').change(function() {
            // show the state dropdown only if a country is selected
            if ($('#countryDropDown option:selected').text != '') {
                $('#stateDropDown').prop('disabled', false);

                var selectedCountry = $(this).val();
                var options = `<option value=0> Select State </option>`
                
                $('#stateDropDown').empty();

                // get the location of the selected country
                $.getJSON("/Home/LoadStateForCountry/?countryId="   selectedCountry, function(data) {
                    $.each(data, function(i, stateDetails) {
                        options  = "<option value="   this['stateId']   ">"   this['stateName']   "</option>"
                    });

                    $("#stateDropDown").html(options)
                })
            
            } else {
                $('#stateDropDown').prop('disabled', true);
            }
        });
    });

Razor Page

<select 
        id="stateDropDown"
        placeholder="Select State"
        asp-items="@ViewBag.StateList">
</select>

CodePudding user response:

Since you want to get data from LoadStateForCountry,you should return stateList in the action:

[HttpGet]
public async Task<IActionResult> LoadStateForCountry(int countryId) {
    var stateCollection = await _service.GetStates(countryId);
    List<StateModel> stateList = stateCollection.ToList();

    //ViewBag.StateList = stateList;
    return new JsonResult(stateList);
}
  • Related