在web.config中:
<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>
}
加载此特定控制器的视图页面后,级联下拉列表无法正常工作。它正在加载部门名称,但不是该特定部门的教师名称。我找不到我的错误。
答案 0 :(得分:0)
GetTeachersByDepartmentId()
方法中的参数名为deptId
而您没有发送deptId
的值(departmentId
只有一个),因此其vakue为{{1并且您的查询将不会返回0
的结果。将ajax调用更改为
.Where(a => a.DepartmentId == 0)
还要注意删除var json = { deptId : deptId }; // change
$.ajax({
type: "POST",
url: '@Url.Action("GetTeachersByDepartmentId", "TeacherCourseAssign")',
data: json, // change
success: function(data) {
....
}
});
选项。您还应该从脚本中删除contentType
。
您的实施还存在其他问题,特别是如果您需要退回视图,我建议您查看this DotNetFiddle中的代码。