我面临以下例外情况:
传递到字典中的模型项的类型为'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>
}
出了什么问题,我不知道,我真的被困在这一个:(任何人请带我离开这个,谢谢你提前......
答案 0 :(得分: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>