【发布时间】:2018-11-29 23:35:15
【问题描述】:
我有一个 Razor 页面视图,它只是从从模型属性检索的列表中生成项目表,如下所示:
@page
@model Agency.Pages.TypeManagement.CategoryType.IndexModel
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-page="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Category[0].CategoryCode)
</th>
<th>
@Html.DisplayNameFor(model => model.Category[0].CategoryName)
</th>
<th>
@Html.DisplayNameFor(model => model.Category[0].CategoryDescription)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Category) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CategoryCode)
</td>
<td>
@Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td>
@Html.DisplayFor(modelItem => item.CategoryDescription)
</td>
<td>
<a asp-page="./Edit" asp-route-id="@item.CategoryId">Edit</a> |
<a asp-page="./Details" asp-route-id="@item.CategoryId">Details</a> |
<a asp-page="./Delete" asp-route-id="@item.CategoryId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
我要做的是根据主表中项目的ID,为表中的每个项目输出一个子表,如果子表中存在任何项目。我知道我可以在 Razor 语句中使用 Model.Category 等属性,但是否也可以根据当前项目的 ID 等值从视图中检索数据?
所以我想要的结果是这样的:
@foreach (var item in Model.Category) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CategoryCode)
</td>
<td>
@Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td>
@Html.DisplayFor(modelItem => item.CategoryDescription)
</td>
<td>
<a asp-page="./Edit" asp-route-id="@item.CategoryId">Edit</a> |
<a asp-page="./Details" asp-route-id="@item.CategoryId">Details</a> |
<a asp-page="./Delete" asp-route-id="@item.CategoryId">Delete</a>
</td>
<table>
<tbody>
@foreach (var subitem in Model.SubCategory) {
<tr>
<td>
@Html.DisplayFor(modelItem => subitem.CategoryCode)
</td>
<td>
@Html.DisplayFor(modelItem => subitem.CategoryName)
</td>
<td>
@Html.DisplayFor(modelItem => subitem.CategoryDescription)
</td>
<td>
<a asp-page="./Edit" asp-route-id="@subitem.CategoryId">Edit</a> |
<a asp-page="./Details" asp-route-id="@subitem.CategoryId">Details</a> |
<a asp-page="./Delete" asp-route-id="@subitem.CategoryId">Delete</a>
</td>
</tr>
}
</tbody
</table
</tr>
}
但是我需要根据主表当前行的item的ID来过滤SubCategory的item。
【问题讨论】:
-
两者之间有联系吗?
-
SubCategory 有一个Category 的外键,即Category.Id
-
过滤当前项目的子类别。
@foreach (var subitem in Model.SubCategory.Where(x => x.CategoryId = item.Id)其中item来自外部foreach循环
标签: c# asp.net-core asp.net-core-2.0 razor-pages