在web.config中:級聯下拉與阿賈克斯mvc4不工作
<add name="Connection" connectionString="Data Source=DESKTOP-SLJTE7M\TAHMINA;Initial Catalog=UniversityDB;Integrated Security=True" providerName="System.Data.SqlClient"></add>`
在控制器:
public ActionResult TeacherCoursAssign()
{
ViewBag.Departments = GetDepartments();
return View();
}
public List<Department> GetDepartments()
{
List<Department> departments = departmentManager.GetAllDepartments();
return departments;
}
public JsonResult GetTeachersByDepartmentId(int deptId)
{
var teachers = GetTeacher();
var teacherList = teachers.Where(a => a.DepartmentId == deptId).ToList();
return Json(teacherList, JsonRequestBehavior.AllowGet);
}
鑑於頁:
<form method="POST" id="myForm">`
....
<label for="departmentId">Select Department</label>
<select name="departmentId" id="departmentId">
<option value="">Select...</option>
@foreach (var department in ViewBag.Departments)
{
<option value="@department.DeptId">@department.DeptName</option>
}
</select>
<label for="teacherId"></label>
<select name="teacherId" id="teacherId"></select>
<input type="submit" id="Submit" value="Submit" class="btn btn-default" />
</form>
@section scripts
{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("#departmentId").change(function() {
$("#myForm").submit(function() {
return false;
});
var deptId = $("#departmentId").val();
$("#teacherId").empty();
var json = { departmentId: deptId };
alart(deptId);
$.ajax({
type: "POST",
url: '@Url.Action("GetTeachersByDepartmentId", "TeacherCourseAssign")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function(data) {
alert(data);
$.each(data, function(key, value) {
alert(key);
$("#teacherId").append('<option value=' + value.TeacherId + '>' + value.TeacherName + '</option>');
});
}
});
});
});
</script>
}
加載我的看法頁面後對於這個特定的控制器級聯下拉不起作用。它正在加載部門名稱,但不是該特定部門的教師名稱。我找不到我的錯誤。
我會建議你使用console.debug()而不是alert()遍及你的代碼:) –