无法在ASP.NET MVC-C#中的级联下拉列表中获取Chil表列表



我有三个表,Student表是CountryId,Country表在SQL Server中是CityId。我可以通过JQuery Ajax在创建学生视图下拉列表中获取所有国家,但不可能以相同的方式获取所有城市。没有加载任何城市,控制台返回此错误:

jquery-3.3.1.js:9600 POSThttp://localhost:4007/Students/GetCityByCountries/2500(内部服务器错误(

在我的Students控制器代码中:

private StudentCountryFileDBEntities1 db = new StudentCountryFileDBEntities1();
public JsonResult GetCountries()
{
return Json(db.Countries.Select(c => new
{
countryId=c.CountryId,
countryName=c.CountryName
}).ToList(),JsonRequestBehavior.AllowGet);
}
public JsonResult GetCityByCountries(int countryId)
{
//var cityList = this.GetCitiesByConId(countryId);
var cities = db.Cities.Where(c=>c.CountryId==countryId).Select(ct => new {
cityId = ct.CityId,
cityName = ct.CityName
}).ToList();
return Json(cities);
}

这是我的观点:

<div class="form-group">
<label for="CountryId" class="control-label col-md-2"><b>Country</b></label>
<div class="col-md-10">
<select class="form-control" id="CountryId" name="CountryName"></select>
@Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<label for="CityId" class="control-label col-md-2"><b>City</b></label>
<div class="col-md-10">
<select class="form-control" id="CityId" name="CityName"></select>
@*@Html.DropDownList("City", ViewBag.Cities as SelectList, "Choose City", new { @class = "inputBox", @id = "CityId" })*@
@Html.ValidationMessageFor(model => model.CityId, "", new { @class = "text-danger" })
</div>
</div>

和Jquery ajax代码:

<script>    
$(document).ready(function () {
$.ajax({
type: "Get",
url: "/Students/GetCountries",
data: "{}",
success: function (data) {
var countries = "<option value=''>Select Country</option>";
for (var i = 0; i < data.length; i++) {
countries += "<option value='" + data[i].countryId + "'>" + data[i].countryName + "</option>";
}
$('#CountryId').html(countries);
}
});
$('#CountryId').change(function () {
$.ajax({
type: "POST",
url: "/Students/GetCityByCountries/" + $('#CountryId').val(),
data: "{id:$('#CountryId').val()}",
success: function (res) {
var cities = "<option value=''>Select Cities</option>";
$('#CityId').html('');
for (var i = 0; i < res.length; i++) {
cities += "<option value='" + res[i].cityId + "'>" + res[i].cityName + "</option>";
}
$('#CityId').html(cities);
}
});
});
</script>
jQuery中的示例。必须将对象传递给控制器。
var objParam = new Object();
objParam.countryId = $('#CountryId').val();
$.ajax({
type: "POST",
url: "/Students/GetCityByCountries/",
contentType: "application/json",
data: JSON.stringify(objParam),
async: false,
success: function (res) {
$('#CountryId').empty();
if (res.length > 0) {
$.each(res, function (key, Data) {
$('#CountryId').append($("<option></option>").val(Data.countryId).html(Data.countryName));
});
}
else {
$('#CountryId').empty();
}
},
error: function (res) {
responseData = null;
}
});

最新更新