C
C#3mo 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}");
}
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?
10 Replies
Kringe
Kringe3mo ago
would a foreach loop fix your issues
Stefanidze
Stefanidze3mo ago
not possible, i want to have limitations by the number on items on the page...
Kringe
Kringe3mo ago
a fair enough you can store I in an outisde var and pass that in
Stefanidze
Stefanidze3mo ago
Well, it's a work-around i may go with, any other options though? I think there should be such functionality in blazor
Kringe
Kringe3mo ago
i think just doing this is fine idk an other way
Stefanidze
Stefanidze3mo ago
Thanks, this works perfectly!
Joschi
Joschi3mo ago
You could alsu use foreach with var i in Enumerable.Range()
Unknown User
Unknown User3mo ago
Message Not Public
Sign In & Join Server To View
Stefanidze
Stefanidze3mo ago
Ok, didn't know about this command