Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write a function in Blazor that dynamically renders elements in a View?

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 :)

like image 942
Broad3857 Avatar asked Dec 31 '22 19:12

Broad3857


1 Answers

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>
like image 93
Peter Morris Avatar answered Jan 20 '23 09:01

Peter Morris