C
C#10mo 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
Kringe10mo ago
would a foreach loop fix your issues
Stefanidze
StefanidzeOP10mo ago
not possible, i want to have limitations by the number on items on the page...
Kringe
Kringe10mo ago
a fair enough you can store I in an outisde var and pass that in
Stefanidze
StefanidzeOP10mo 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
Kringe10mo ago
i think just doing this is fine idk an other way
Stefanidze
StefanidzeOP10mo ago
Thanks, this works perfectly!
Joschi
Joschi10mo ago
You could alsu use foreach with var i in Enumerable.Range()
Unknown User
Unknown User10mo ago
Message Not Public
Sign In & Join Server To View
Stefanidze
StefanidzeOP10mo ago
Ok, didn't know about this command
Want results from more Discord servers?
Add your server