blazorblazor-server-side

blazor variable argument passing to onclick function


I want to pass the int i into the button onclick function for each list item. I expected the "clickItem" function will receive 0..2 for correspondig list item. But it come out that it always receive 3 as argument. It seems that the variable i in the clickItem(i) is not evaluated at the time of render of the for loop. I have tried changing it to "clickItem(@i)" but it is still the same. What should I do? (I am using blazor server side, .net core 3 preview 5)

        @for (int i = 0; i < 3; i++)
        {
            <li> item @i <button onclick=@(() => clickItem(i))>Click</button> </li>
        }

enter image description here


Solution

  • This is a classic C# problem with lambda's, 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 =>.