您正在返回一个匿名对象,而您的视图是强类型的IEnumerable<mvc4application.models.employee>
.
我强烈建议您编写一个视图模型,该模型将满足您的视图的要求,并包含您想要在此视图中使用的信息:
public class EmployeeViewModel
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string ManagerName { get; set; }
public string Designation { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
然后调整您的 LINQ 查询,以便将各种域 EF 对象投影到视图模型中:
IEnumerable<EmployeeViewModel> employees =
from m in t.Employees
join e1 in t.Employees on m.ManagerID equals e1.EmployeeID
select new EmployeeViewModel
{
EmployeeID = m.EmployeeID ,
Name = m.Name,
ManagerName = e1.Name,
Designation = m.Designation,
Phone = m.Phone,
Address = m.Address
};
return View(employees.ToList());
最后使您的视图强类型化到视图模型:
@model IList<EmployeeViewModel>
现在您可以提供信息:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Manager name</th>
<th>Designation</th>
<th>Phone</th>
<th>Address</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(x => x[i].EmployeeID)</td>
<td>@Html.DisplayFor(x => x[i].Name)</td>
<td>@Html.DisplayFor(x => x[i].ManagerName)</td>
<td>@Html.DisplayFor(x => x[i].Designation)</td>
<td>@Html.DisplayFor(x => x[i].Phone)</td>
<td>@Html.DisplayFor(x => x[i].Address)</td>
</tr>
}
</tbody>
</table>