This is a classic problem, but slightly new in the context of Blazor.
You need to make a copy of i
because otherwise the lambda “captures the loop variable”. Capturing the copy is OK.
@for (int i = 0; i < 3; i++)
{
int localCopy = i;
<li> item @i <button onclick=@(() => clickItem(localCopy))>Click</button> </li>
}
Note that this is an issue with for()
loops but not with foreach()
, and only on the right hand side of a =>
.