Hi!
I working with asp.net core 3.1 and I need help because I can't do load the dropdown "cities" when I select a Country.
This is my code.
<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>
AccountController
public async Task<JsonResult> GetCitiesAsync(int countryId)
{
var country = await _countryRepository.GetCountryWithCitiesAsync(countryId);
return Json(country.Cities.OrderBy(c => c.Name));
}
@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.