I have a table that has ID, Name, ParentId. So basically, for example I could have those entries inside database table –
How table structure actually looks like
And what I need to do is create a table that will have nested rows and display child(s) on expand
- Name1
- Name2
- Name5
- Name3
- Name4
- Name2
- Name7
- Name6
But there could be more nesting than just 3. So I would need to use some kind of recursive function inside view. Currently I’ve been using this code
<tbody>
@foreach (var entity in Model)
{
if (entity.ParentId == null)
{
<tr>
<td><button class="expandButton" type="button" ></button></td>
<td>
@entity.Name
</td>
<td>
<a asp-action="ManipulateEntity" asp-route-id="@entity.Id">Manipulate</a>
</td>
</tr>
int child = 1;
foreach (var childEntity in Model.Where(i => i.ParentId == entity.Id))
{
<tr>
<td>
@childEntity.Name
</td>
<td>
<a asp-action="ManipulateEntity" asp-route-id="@childEntity.Id">Manipulate</a>
</td>
</tr>
child++;
}
}
}
But unfortunately, this shows results only for the first parent and his childs, when there are childs of childs, it bumps out and shows just for the first parent and his childs. As you can see, I am iterating through Model which is basically List
How can this be done on View side? I’ve provided minimum code to understand my current logic, which as I’ve said just shows first parent and his childs, but I am unable to figure it out on my own what should I change to make this work.