我在MVC控制器中具有按国家/地区ID获取城市的功能 我有java脚本函数,在控制器中调用此方法
[HttpPost]
public ActionResult GetcitiesBycountry(string selectedValue)
{
List<string> cityList = new List<string>();
if (selectedValue != null && selectedValue.Length > 0)
{
using (InstructoroEntities dataContext = new InstructoroEntities())
{
int ID = int.Parse(selectedValue);
List<string> getcities = dataContext.Cities.Where(query => query.CountryID
==ID).Select(q => q.CityName).ToList();
cityList = getcities;
}
}
return Json(new { CityList = cityList });
}
<script type="text/javascript">
$("#CountryID").change(function () {
var selectedValue = $(this).val();
$.ajax({
url: '@Url.Action("GetcitiesBycountry", "Registration")',
type: 'POST',
data: { "selectedValue": selectedValue },
dataType: 'json',
success: function (response) {
var items = "";
$.each(response.CityList, function (i, item) {
items += "<option value=\"" + item + "\">" + item + "</option>";
});
$("#CityName").html(items);
},
error: function (error) {
}
});
});
</script>
我只想获取城市ID和名称而不是名称 最好的问候。
答案 0 :(得分:2)
改变如下。
C#:使用
var getcities = dataContext.Cities.Where(query => query.CountryID ==ID)
.Select(q => new{q.CityName, q.CityID}).ToList();
}
}
return Json(getcities);
而不是
List<string> getcities = dataContext.Cities.Where(query => query.CountryID
==ID).Select(q => q.CityName).ToList();
cityList = getcities;
}
}
return Json(new { CityList = cityList });
JQuery:使用
$.each(response, function (i, item) {
items += "<option value=\"" + item.CityID + "\">" + item.CityName + "</option>";
});
而不是
$.each(response.CityList, function (i, item) {
items += "<option value=\"" + item + "\">" + item + "</option>";
});