我有一个名为Models的列表,其中包含ID、标题和变体。变体是一个列表,其中包含另一个元素Id、ModelID和Title。 我的问题是如何循环遍历Variants列表,它是Models的子列表。
Repository.cs
public class Repository : IRepository
{
private List<ModelSearch> _list = new List<ModelSearch>();
public Repository()
{
populateList();
}
private void populateList()
{
_list.Add(new ModelSearch
{
ID = 1,
Title = "Scorpio",
Variants = new List<Variant> {
new Variant { ID = 1, ModelID = 1, Title="scorpio1" },
new Variant { ID = 2, ModelID = 1, Title="scorpio2" },
new Variant { ID = 3, ModelID = 1, Title="scorpio3" }
}
});
_list.Add(new ModelSearch
{
ID = 2,
Title = "Bolero",
Variants = new List<Variant> {
new Variant { ID = 1, ModelID = 2, Title="Bolero1" },
new Variant { ID = 2, ModelID = 2, Title="Bolero2" },
new Variant { ID = 3, ModelID = 2, Title="Bolero3" }
}
});
}
public IEnumerable<ModelSearch> GetAll()
{
return _list.AsEnumerable();
}
}
这是我的Index.cshtml文件:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Variants.First().Title)
</td>
</tr>
}
我希望在这个表格中同时显示相应的变体。我该如何实现?
ModelSearchController.cs
public class ModelSearchController : Controller
{
private IRepository _repo;
public ModelSearchController()
{
_repo = new Repository.Repository();
}
public IActionResult Index()
{
var modelList = _repo.GetAll(
return View(modelList);
}
}