Reputation: 463
I have an object called BusinessUnit which contains a list of child business units and I need a function that renders < li> elements for every child under its parent. The code I have so far is below:
<ul id="Level0">
@foreach (var bizUnit in businessUnitViewModel.BusinessUnitInfos)
{
<li>
<span>@bizUnit.BusinessUnitName</span>
<ul class="nested">
@foreach (var childOfbizUnit in bizUnit.Children)
{
<li>@childOfbizUnit.BusinessUnitName</li>
}
</ul>
</li>
}
</ul>
The nested foreach is basically the same as the first one, but hardcoding them limits how many hierarchical levels I can have. I need a function like this:
public void HasKids(BusinessUnitInfo bizUnit)
{
foreach (var bizUnitChild in bizUnit.Children)
{
//Render an <li> tag element with bizUnitChild's
name<li>bizUnitChild.Name</li>
HasKids(bizUnitChild);
}
}
Does anyone know what I can do for the comment in the last code block; can I use C# code to dynamically render a list tag? Thans :)
Upvotes: 7
Views: 4258
Reputation: 578
I made some improvements for Peter Morris's code:
<li>
@Item.Name
@if (Item.Children != null && Item.Children.Any())
{
<ul class="@Level">
@foreach(var child in Item.Children)
{
<ShowItem Item=@child Level="@(Level + 1)" @key=child/>
}
</ul>
}
</li>
@code {
[Parameter] public MyElementClass Item { get; set; }
[Parameter] public int Level { get; set; }
}
I added null check, because I had problems when the property was null, fixed a typo in the Id of the ul and changed the id to class.
Upvotes: 2
Reputation: 23224
If the structure is a tree then you effectively need a recursive component.
Note: For performance reasons you should always use the @key
directive when generating UI markup from a loop. You can read more at Blazor University.
<li>
@Item.Name
if (@Item.Children.Any())
{
<ul id="@level">
@foreach(var child in Item.Children)
{
<ShowItem Item=@child Level="@(Level + 1)" @key=child/>
}
</ul>
}
</li>
@code {
[Parameter] MyElementClass Item { get; set; }
[Parameter] int Level { get; set; }
}
In your main page, you just do this
<ul level="0">
@foreach(var item in TopLevelItems)
{
<ShowItem Item=@item Level=1 @key=item/>
}
</ul>
Upvotes: 12