我面临以下异常:
传递到字典中的模型项的类型为"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]"。
这是我的模型,员工.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; }
}
部门.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; }
}
和我的员工控制器的索引操作,其中异常生成:
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>
}
出了什么问题,我不知道,我严重地被困在了这个:(上,任何人请带我离开这里,提前谢谢。.
本质上,代码:
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>