Skip to content
Advertisement

How to set ASP-Items value for SelectList via javascript ajax call

I have a states dropdown on a form, and when a user selects a state, I want the cities dropdown to populate with just the cities pertaining to that state.

I have 2 Select Boxes in my form view:

        <div class="col-md-3 py-2">
            <label asp-for="@Model.Quote.CompanyState" class="form-label"></label>
            <select asp-for="@Model.Quote.CompanyState" asp-items="@Model.States" class="form-select">
                <option selected>Choose...</option>
            </select>
            <span asp-validation-for="@Model.Quote.CompanyState" class="text-danger"></span>
        </div>
        <div id="cityDDL" class="col-md-3 py-2" style="display:none;">
            <label asp-for="@Model.Quote.CompanyCity" class="form-label"></label>
            <select asp-for="@Model.Quote.CompanyCity" asp-items="@Model.Cities" class="form-select">
                <option selected>Choose...</option>
            </select>
            <span asp-validation-for="@Model.Quote.CompanyCity" class="text-danger"></span>
        </div>

Then I have Javascript that gets the cities via ajax when the state is selected:

    $('#Quote_CompanyState').on('change', function () {
        var state = $('#Quote_CompanyState Option:Selected').val();
        Quote.GetCitiesDropDown(state);
    })

My ajax call to the controller:

Quote.GetCitiesDropDown = function (state) {

    $.ajax({
        url: Global.basePath + 'Quote/GetCitiesDropDown',
        type: "POST",
        dataType: 'json',//if returning view, must be html, else use json
        data: {state: state},
        cache: false,
        success: function (data) {
            console.log(data);
            $('#cityDDL').show();
        },
        error: function (xhr, status, error) {
            var err = JSON.parse(xhr.responseText);
            alert('Error: ' + err.quote_error[0]);
        },
        complete: function (data) {
        }
    });
}

My controller that gets the SelectListItems of Cities pertaining to the selected state:

[HttpPost]
public IActionResult GetCitiesDropDown(string state)
{
    //var statesJSON = _config.GetSection("UnitedStatesList").Get<Dictionary<string,string>>();
    var cities = _config.GetSection("CitiesByState").GetSection(state).Get<Dictionary<string, string>>();
    var citiesDDIs = cities.Select(city => new SelectListItem
    {
        Value = city.ToString(),
        Text = city.ToString()
    }).ToList();
    return Json(citiesDDIs);
}

Right now it returns the object to the success part of my ajax call, but how do I set the option items for that dropdown view javascript. This is what the data looks like that I get via javascript… I was hoping to set the asp-items value… but I am not sure how to do that exactly with Javascript. These are the cities it returns for Alabama, for example: enter image description here

Advertisement

Answer

So returning a dictionary from the controller sends an object to the ajax call. I had to figure out how to loop through the object in JS:

success: function (data) {
    console.log(data);
    $('#cityDDL').show();
    var citiesSelect = $('#Quote_CompanyCity');
    $(citiesSelect).empty();
    $(citiesSelect).append($(`<option selected>Choose ${state} city</option>`));
    for (var key in data) {
        if (data.hasOwnProperty(key)) {
            $(citiesSelect).append($(`<option value="${data[key]}">${data[key]}</option>`));
        }
    }

},
Advertisement