2016-01-21 56 views
0

我面對下面的異常類型的模型項:傳遞到字典的模型產品類型列表中,但本詞典需要的IEnumerable

傳遞到字典的模型項的類型爲「 System.Collections.Generic.List 1[DropDownList.Models.Department]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [DropDownList.Models.Employee]'。

這裏是我的模型, Employee.cs:

public class Employee 
{ 
    public int EmployeeId { get; set; } 
    public string EmployeeName { get; set; } 
    public int DepartmentId { get; set; } 

    public virtual Department Department { get; set; } 
} 

Department.cs:

public class Department 
{ 
    public int DepartmentId { get; set; } 
    public string DeptCode { get; set; } 
    public string DepartmentName { get; set;} 
    public string Syscode { get; set; } 

    public virtual ICollection<Employee> Employees { get; set; } 
} 

和我EmployeesController的指數動作,在異常產生:

public ActionResult Index() 
{ 
var employees = 
      from dept in db.Departments 
      select new 
      { 
       dept, 
       depts = from emp in dept.Employees 
         where dept.Syscode == "isols123" 
         select dept 
      }; 
     var employs = employees 
      .AsEnumerable() 
      .Select(m => m.dept); 
     return View(employs.ToList()); 
} 

這裏是我的索引視圖:

@model IEnumerable<DropDownList.Models.Employee> 
. 
. 
@foreach (var item in Model) { 
<tr> 
    <td> 
     @Html.DisplayFor(modelItem => item.Department.DepartmentName) 
    </td> 
    <td> 
     @Html.DisplayFor(modelItem => item.EmployeeName) 
    </td> 
</tr> 
} 

到底哪裏出問題了,我不知道,我認真地停留在這一個:(,任何人請帶我離開這裏,在此先感謝..

回答

1

從本質上講,代碼:

public ActionResult Index() 
{ 
var employees = 
      from dept in db.Departments // This makes dept of type Department 
      select new 
      { 
       dept, 
       depts = from emp in dept.Employees 
         where dept.Syscode == "isols123" 
         select dept 
      }; 
     var employs = employees 
      .AsEnumerable() 
      .Select(m => m.dept); // Selects Department 
     return View(employs.ToList()); 
} 

返回Departments列表(即使壽的變量被稱爲employs)和視圖期望它的Employees列表。

這兩個應該匹配它的工作。

假設LINQ查詢是正確的,這將使其預期在視圖部門列表:

@model List<DropDownList.Models.Department> 
+0

先生,其實我想僱員窗體上創建部門的下拉列表中,因此,如果這是問題,我該如何解決它,我應該做什麼改變? –

+0

哦,我的不好,我正在選擇部門名單,而我應該選擇員工名單,謝謝你的時間,先生。 –

相關問題