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 :)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With