我正在尝试在选择城市时在下拉列表中显示教练列表。这是我的2个下拉菜单;
<td>
<select id="ddlCity" class="form-control" onchange="getCoaches();">
@foreach (var item in ViewBag.Cities)
{
<option value="@item.id">@item.City_Name</option>
}
</select>
</td>
<td>
<select id="ddlCoach" class="form-control">
</select>
</td>
此处是返回教练列表的函数。工作正常,并返回教练名单;
[HttpPost]
public JsonResult getCoaches(string cityId)
{
int intcityId = Convert.ToInt32(cityId);
var coaches = db.tbl_Coordinators.Where(x => x.fk_cityid == intcityId).ToList();
return Json(coaches);
}
这里是ajax代码。取而代之的是,在填充教练下拉菜单时,它会跳至错误。
function getCoaches(){
$('#ddlCoach option').remove();
alert('in function');
var selected_City = $("#ddlCity :selected").text();
var selected_City_Value = $("#ddlCity :selected").val();
alert(selected_City_Value);
$.ajax({
type: "POST",
url: "/Admin/getCoaches",
datatype: "Json",
data: { cityId: selected_City_Value },
success: function (data) {
debugger;
console.log(data);
alert('success' + data);
$.each(data, function (index, value) {
$('#ddlCoach').append('<option value="' + value.id + '">' + value.Cordinator_Name + '</option>');
});
}
,error: function(jqXHR, status,err){
alert("Error");
}
});
}
我尝试了许多其他解决方案,但是都没有用。我想ajax代码有问题,我不知道如何调试它。
答案 0 :(得分:1)
首先按如下所示编写getCoaches
控制器POST
方法:
[HttpPost]
public JsonResult getCoaches(int cityId)
{
var coaches = db.tbl_Coordinators.Where(x => x.fk_cityid == cityId).ToList();
var coachSelectList = new SelectList(coaches , "Id", "Cordinator_Name"); // ensure that your coach model class primary key name is `Id`
return Json(coachSelectList);
}
然后按如下所示编写GetCoaches
javaScript方法:
function getCoaches(){
var ddlCoachSelector = $('#ddlCoach');
ddlCoachSelector.empty();
var selectedCity = $("#ddlCity").val();
$.ajax({
type: "POST",
url: "/Admin/getCoaches",
data: { cityId: selectedCity },
success: function (data) {
if(data.length> 0){
ddlCoachSelector.append($("<option>").val("").text("Select Coach"));
$(data).each(function(index, item) {
ddlCoachSelector.append($("<option>").val(item.Value).text(item.Text));
});
} else{
ddlCoachSelector.append($("<option>").val("").text("Coach list empty!"));
}
},
error: function(jqXHR, status,err){
alert("Error");
}
});
}
希望它对您有用。