Home > Software engineering >  Blazor Pass List of NavItems to NavMenu as parameter
Blazor Pass List of NavItems to NavMenu as parameter

Time:11-17

I have the normal NavMenu and added a Parameter

[Parameter]
public List<NavItem> navItems {get, set;}

My Nav Item:

[Parameter]
  public string DisplayName {get, set;}

[Parameter]
  public string Href {get, set;}

So now in the MainLayout I want to add the NavMenu and add the List of NavItems with Parameters.

If I create the List of NavItems and assign the parameters I got the warning BL0005.

How can I do it the right way? (Not ignoring/disabling the warning)

Thanks

CodePudding user response:

Don't use a List of NavItems. Use a list of DisplayName/HRef pairs (ViewModels) instead.

The lifecycle of Blazor components is (should be) managed by Blazor. Everytime you do something like new NavItem() you are doing it wrong.

So create a ViewModel for your menu.

CodePudding user response:

You may change the List in NavMenu to List<RenderFragment> and then define them like:

navItems.Add(@<a href="dummy.com">Test 1</a>);

And use them like:

@foreach (var navItem in navItems)
{
    @navItem
}
  • Related