当另一个选择列表发生更改时,Ajax调用填充选择列表

继这篇文章之后 ,我试图在另一个“国家/地区”选择列表发生变化时填充一份“城市”选择列表。 我采用了与链接post相同的方法,并按照下面的概述实现了Darin对成功的建议()。 它“大部分时间”工作得很好(这真的很奇怪)。 我的意思是,在我所有’国家’中,90%的更改事件返回选择列表项目对象,另外10%返回单个字符串值。 为什么会有所不同? 它应该工作与否……

视图

 

List of countries from Model...

Select a country first...
$('#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( $('', { value: this.Value, text: this.Text }) ); }); } }); });

调节器

  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 cities = new List(); 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( $('