我正在使用Bootstrap的选择器插件。当CountryList发生变化时,我在数据库中动态地选择该国的现有城市,并将数据传输到CityList。但是,即使选择了第一个选项,选择器的头也没有选择任何选项。如果所选国家的数据库中有一个城市,即使单击该城市,所选的任何内容也不会改变。事实上,我可以得到城市的价值来选择,但它说什么都没有选择。我怎么才能解决这个问题?
选择者党卫军:

回应SS:

非常感谢您的答复。
CountryList变化函数
$("#CountryList").change(function() {
var countryId = $('#CountryList option:selected').val();
$.ajax({
type: "POST",
url: "@Url.Action("GetCities", "Project")",
data: { countryId: countryId },
dataType: "text",
success:
function(response) {
var parsedResponse = jQuery.parseJSON(response);
console.log(parsedResponse);
var option = "";
for (var i = 0; i < parsedResponse['cityList'].length; i++) {
if (i == 0) {
var city = parsedResponse['cityList'][i].text;
var cityId = parsedResponse['cityList'][i].value;
option += `<option selected value="${cityId}">${city}</option>`;
} else {
var city = parsedResponse['cityList'][i].text;
var cityId = parsedResponse['cityList'][i].value;
option += `<option value="${cityId}">${city}</option>`;
}
}
$("#CityList").html(option);
$("#CityList").selectpicker('refresh');
}
});
});项目控制器GetCities动作
[HttpPost]
public async Task<JsonResult> GetCities(int countryId)
{
var model = new AddProductViewModel();
var cityList = await _cityService.GetAllAsyncByCountryId(countryId);
model.CityList = new SelectList(cityList, "Id", "Name");
var firstCity = cityList.First();
model.CountryDefaults = await _countryDefaultService.GetAllAsyncByCountryCityId(countryId, firstCity.Id);
model.CountryDefault = _countryDefaultService.GetByCountryCityId(countryId, firstCity.Id);
JsonConvert.SerializeObject(model);
return Json(model);
}发布于 2021-07-07 08:37:40
首先,我们需要在下拉列表中附加选项并刷新选择器,现在我们必须动态地选择第一个选项,然后再次刷新选择器。这就是选择器的工作原理。
检查下面的代码
var option = "";
for (var i = 0; i < parsedResponse['cityList'].length; i++) {
var city = parsedResponse['cityList'][i].text;
var cityId = parsedResponse['cityList'][i].value;
option += `<option value="${cityId}">${city}</option>`;
}
$("#CityList").html(option);
$("#CityList").selectpicker('refresh');
$("#CityList").val($('#CityList option:first').val());
$("#CityList").selectpicker('refresh');https://stackoverflow.com/questions/67196853
复制相似问题