0

I have a little Blazor app (server side in the unlikely case that's relevant) in which I want to dynamically create some links based on fields of objects in a list - one field is the URL that the link should direct to and another field is just the text that should be shown on the NavLink component. So this is how this class looks like (simplified for this purpose):

public class portfolioname
{
     public string name { get; set; }

     public string url { get; set; }
}

In my app I create the objects and populate the list, which is called porturls - everything works fine.

The relevant part of my Razor page (which is just a modified version of the MS Sample Blazor app) then looks like this:

@for (int i = 0; i < porturls.Count; i++)
{                        
    <li class="nav-item px-3">                               
           <NavLink class="nav-link" href=@porturls[i].url Match=@NavLinkMatch.All>                            
                @porturls[i].name
           </NavLink>                                  
    </li>
}    

This causes an index out of range error on the @porturls[i].name line.

However everything works fine when I either simply leave out the @porturls[i].name line (the links work taking the correct url from @porturls[i].url there is just no text shown) or when I replace the NavLink components by standard html <a href=@porturls[i].url>.

Any advice what I'm doing wrong or what's the issue with the NavLink component here? Not sure what else I could try, I would prefer to use the NavLink component here.

  • [Polite] I voted to close your question as it's a common question we see with many answers on SO. Search "Blazor For Loop". See - https://stackoverflow.com/questions/35365350/closures-behaving-differently-in-for-and-foreach-loops - https://stackoverflow.com/questions/69971645/why-cant-i-use-the-loop-counter-in-blazor and many more . – MrC aka Shaun Curtis Mar 14 '23 at 12:06
  • Thx, the second link fixed it - it works if I use a local placeholder variable instead of the loop iterator i - however it's still not fully clear as to why this is only a problem inside the the NavLink component AND only for the text that should be shown not for the hyperlink itself. – Hatzegopteryx Mar 14 '23 at 12:32
  • `href` is a element, so the string is materialized in the loop. The Name is in a `RenderFragment` and is a reference. In general stick with `@foreach`: the problem goes away. – MrC aka Shaun Curtis Mar 14 '23 at 15:01

0 Answers0