继this post之后,当另一个“国家”选择列表发生更改时,我尝试填充“城市”选择列表。我遵循与链接帖子相同的方法,并如下所述实现达林对成功的建议()。它在“大多数”时间都工作得很好(这真的很奇怪)。我的意思是,在我的所有“国家/地区”中,90% 的更改事件返回选择列表项对象,其他 10% 返回单个字符串值。为什么会有所不同?它应该工作或不工作...
查看
<!--Country-->
<div class="form-group col-md-3">
<label class="control-label ">City </label>
<br />
<select id="Country" name="Country" class="form-control">
<option value="">List of countries from Model...</option>
</select>
</div>
<!--City-->
<div class="form-group col-md-3">
<label class="control-label ">City </label>
<br />
<select id="City" name="City" class="form-control">
<option value="">Select a country first...</option>
</select>
</div>
<!--Inside my script -->
<script>
$('#Country').change(function () {
var selectedValue = $(this).val();
$.ajax({
url: '@Url.Action("CityDropDownList", "Home")',
type: "GET",
data: { country: selectedValue },
success: function (result) {
var cityDropDownList = $('#City');
cityDropDownList.empty();
$.each(result, function () {
cityDropDownList.append(
$('<option/>', {
value: this.Value,
text: this.Text
})
);
});
}
});
});
</script>
Controller
public JsonResult CityDropDownList(string country)
{
var results = (from c in db.PageStats
where c.Country.Equals(country)
orderby c.City
select c.City).ToList().Distinct();
//db.PageStats.Where(x => x.Country.Equals(country)).OrderBy(x => x.City).Select(x => x.City).Distinct().ToList();
List<SelectListItem> cities = new List<SelectListItem>();
foreach(var item in results)
{
SelectListItem city = new SelectListItem
{
Text = item,
Value = item
};
cities.Add(city);
}
return Json(cityList, JsonRequestBehavior.AllowGet);
}
最佳答案
已解决
$('#Country').change(function () {
var selectedValue = $(this).val();
$.get({
url: '@Url.Action("CityDropDownList", "Home")',
data: { country: selectedValue },
success: function (result) {
alert(result);
var cities = $('#City');
cities.empty();
$.each(result, function () {
cities.append(
$('<option>', {
value: this.Value
}).text(this.Text)
);
});
}
});
});
关于jquery - 当另一个选择列表更改时,Ajax 调用填充选择列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393409/