我是MVC的新手。我有两个不同的表tblEmployee和tblDepartment,这两个表的常用字段是部门ID。 我想在不同的表格中显示部门及其员工的列表。
这是我的控制者:
public ActionResult Index()
{
List<Department> departments = db.Departments.ToList();
List<Employee> ep = new List<Employee>();
var q = from depa in db.Departments
join emp in db.Employees
on depa.Id equals emp.DepartmentId
select new
{
Name = emp.Name
};
ViewBag.Data = q;
return View(departments);
}
这是我的观点:
@model IEnumerable<EmployeeDetails.Models.Department>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach (var item in Model) {
<table border="1">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
</tr>
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
<tr>
<th>
Name
</th>
<th>
Gender
</th>
<th>
City
</th>
@foreach (var it in ViewBag.Data)
{
<tr>
<td>
@it
</td>
</tr>
}
</tr>
</table><br/>
}
但是我得到了每个部门表中的所有员工,而o / p也不清楚。 请帮助我。
答案 0 :(得分:1)
假设你已正确地在数据库中定义了你的关系(外键),这应该可行:
在控制器中:
public ActionResult Index()
{
List<Department> departments = db.Departments.Include("Employees").ToList();
return View(departments):
}
在视图中:
@model IEnumerable<EmployeeDetails.Models.Department>
<h2>Departments</h2>
@foreach (var item in Model) {
<table border="1">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
</tr>
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
<tr>
<th>
Name
</th>
<th>
Gender
</th>
<th>
City
</th>
</tr>
@foreach (Employee emp in item.Employees)
{
<tr>
<td>
@emp.Name
</td>
</tr>
}
</table>
<br />
}