我有一个Razor Page视图,该视图仅从从Model属性检索的列表中生成项目表,如下所示:
@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之类的值从View检索数据?
所以我最后想要的是这样的东西:
@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>
}
但是我需要根据主表当前行中项目的ID来过滤SubCategory项目。
答案 0 :(得分:2)
在当前项目/行的标识符上过滤子类别。
@foreach (var item in Model.Category) {
//...omitted for brevity
var subItems = Model.SubCategory.Where(x => x.CategoryId = item.Id);
if(subItems.Any()) {
<table>
<tbody>
foreach (var subitem in subItems) {
//...omitted for brevity
其中item
来自外部foreach
循环。
引用Using the Razor Syntax: Combining Text, Markup, and Code in Code Blocks