2016-05-01 56 views
1

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

加載我的看法頁面後對於這個特定的控制器級聯下拉不起作用。它正在加載部門名稱,但不是該特定部門的教師名稱。我找不到我的錯誤。

+0

我會建議你使用console.debug()而不是alert()遍及你的代碼:) –

回答

0

參數在GetTeachersByDepartmentId()方法命名爲deptId和你不發送消息deptId值(只有一個departmentId),所以其vakue是0和您的查詢將返回沒有結果.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選項。您還應該從腳本中刪除$("#myForm").submit(function() { return false; });

您的實施還有其他問題,特別是如果您需要返回視圖,我建議您查看this DotNetFiddle中的代碼。

+0

謝謝你..這對我來說是一個很大的hlp:D –