C#C
C#2y ago
Stefanidze

✅ How can i bind a value to an item on render in blazor?

I use the following layout:
inject NevigationManager nav

<ul>
  @for (int i = 0; i < ItemList.count, i++){
    <li @onclick="() => redirect(i)">
      @* some code *@
    </li>
  }
</ul>
@code{
  public IReadOnlyCollection<Item>? ItemList;
  
  //some code

  void redirect(int index){
    nav.NavigateTo($"/db?item={ItemList!.ElementAt(index).Id}");
  }

But when the user clicks on an item it tries to get next i value, for example if a database has 3 items (including null item) i will be 4, resulting in an IndexOutOfRangeException. How can i make i value somehow bind to the item on render in a way that i can get it in code?
Was this page helpful?