简体   繁体   中英

Cascade Dropdownlist using asp.net core 3.1 mvc

I am unable to populate the CityId select via Ajax when i choose a country from the CountryId select.

I tried changing the jquery version and it still doesn't work.

Can someone tell me where my mistake is?

View:

<div class="row">
    <div class="col-md-4 offset-md-4">
    <form method="post">
        <div asp-validation-summary="ModelOnly"></div>
        <div class="form-group">
            <label asp-for="CountryId" class="control-label"></label>
            <select asp-for="CountryId" asp-items="Model.Countries" class="form-control"></select>
            <span asp-validation-for="CountryId" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="CityId" class="control-label"></label>
            <select asp-for="CityId" asp-items="Model.Cities" class="form-control"></select>
            <span asp-validation-for="CityId" class="text-danger"></span>
        </div>              
    </form>
    </div>
</div>

Controller:

public async Task<JsonResult> GetCitiesAsync(int countryId)
{
    var country = await _countryRepository.GetCountryWithCitiesAsync(countryId);
    return Json(country.Cities.OrderBy(c => c.Name));
}

Javascript code for calling GetCitiesAsync via Ajax:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        $(document).ready(function () {
            $("#CountryId").change(function () {
                $("#CityId").empty();
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetCitiesAsync")',
                    dataType: 'json',
                    data: { countryId: $("#CountryId").val() },
                    success: function (cities) {
                        $("#CityId").append('<option value="0">(Select a city...)</option>');
                        $.each(cities, function (i, city) {
                            $("#CityId").append('<option value="'
                                + city.id + '">'
                                + city.name + '</option>');
                        });
                    },
                    error: function (ex) {
                        alert('Failed to retrieve cities.' + ex);
                    }
                });
                return false;
            })
        });
    </script>
}

Thanks!

It works fine for me.

I made a small working example from your code: dotnetfiddle .

Notice that i haven't changed your js code. which means that the problem is one of the following:

  • You're returning the json data in a different form than expected from the client side.
  • You have a corrupt script.
  • You have a missing script.

Check your browser console for errors, if there aren't any, try to change your running scripts ie, change your CDN if you're using one.

Example code:

View:

<div class="container">
    <div class="col-md-6 col-md-offset-3">
        @using (Html.BeginForm())
        {
            <select class="form-control" name="CountryId" id="CountryId">
                <option value="0" selected>Select</option>
                <option value="1">US</option>
                <option value="2">UK</option>
            </select>
            <select class="form-control" name="CityId" id="CityId">
            </select>
        }
    </div>
</div>

Javascript:

$(function()
{       
    $("#CountryId").change(function () 
    {
        $("#CityId").empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetCitiesAsync")',
            dataType: 'json',
            data: { countryId: $("#CountryId").val() },
            success: function (cities) {
                if (cities.length == 0)
                   return;

                $("#CityId").append('<option value="0">(Select a city...)</option>');
                $.each(cities, function (i, city) {
                    $("#CityId").append('<option value="'
                        + city.id + '">'
                        + city.name + '</option>');
                });
            },
            error: function (ex) {
                alert('Failed to retrieve cities.' + ex);
            }
        });
        return false;
    })

});

Controller:

[HttpPost]
public JsonResult GetCitiesAsync(int countryId)
{               
    if (countryId == 1)
    { 
        return Json(new List<dynamic>() { new { name = "NewYork", id = 1 }, new { name = "LosAngeles", id = 2 }});
    }
    else if (countryId == 2)
    {   
        return Json(new List<dynamic>() { new { name = "London", id = 1 }, new { name = "Manchester", id = 2 }}); 
    }
    else
    {
        return Json("");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM