gpt4 book ai didi

javascript - 返回城市 ID 和名称 JSON MVC4

转载 作者:行者123 更新时间:2023-11-30 17:09:22 25 4
gpt4 key购买 nike

我在 MVC Controller 中有按国家 ID 获取城市的功能我有在 Controller 中调用此方法的 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 和名称,而不是仅获取名称最好的问候。

最佳答案

改变如下。

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>";
});

关于javascript - 返回城市 ID 和名称 JSON MVC4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27318678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com