问题描述:

In web.config:

<add name="Connection" connectionString="Data Source=DESKTOP-SLJTE7M\TAHMINA;Initial Catalog=UniversityDB;Integrated Security=True" providerName="System.Data.SqlClient"></add>`

In controller:

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

}

In view page:

<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>

}

After loading my view page for this specific controller the cascading dropdown is not working. It's loading the department name but not that teacher name for that specific department. I couldn't find my mistake.

网友答案:

The parameter in your GetTeachersByDepartmentId() method is named deptId and your not sending a value for deptId (only one for departmentId), so its vakue is 0 and your query would return no results for .Where(a => a.DepartmentId == 0). Change ajax call to

var json = { deptId : deptId }; // change
$.ajax({
    type: "POST",
    url: '@Url.Action("GetTeachersByDepartmentId", "TeacherCourseAssign")',
    data: json, // change
    success: function(data) {
        ....
    }
});

Note also to remove the contentType option. You should also remove $("#myForm").submit(function() { return false; }); from your script.

There are also other issues with your implementation, particularly if you need to return the view and I recommend you review the code in this DotNetFiddle.

相关阅读:
Top