5

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

Raymond Wong
  • 282
  • 1
  • 3
  • 9

2 Answers2

13

This is a classic, but slightly new in the context of Blazor.

You need to make a copy because otherwise the lambda 'captures' the loop variable. Capturing the copy is OK.

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

Note that this is an issue with for() loops but not with foreach().

Henk Holterman
  • 250,905
  • 30
  • 306
  • 490
  • Thanks Henk, it works. But I don't understand the underlying difference. Why the "copy" and "i" will be treated differently? Is there some reference for me to further study? – Raymond Wong Jun 03 '19 at 11:26
  • 1
    See my answer here for an explanation: https://stackoverflow.com/questions/55278600/calling-function-from-generated-button-in-blazor/55278788#55278788 – enet Jun 03 '19 at 11:32
  • 1
    You can google " lambda 'captures' the loop variable" for dozens of Q+A, mostly on SO. That's why I didn't make this answer too long. – Henk Holterman Jun 03 '19 at 12:15
0

I tried this, and it worked. Hope it seems helpful to you.

 @foreach (var item in ListOfUser)
            {
                <tr>
                    <td>@item.FirstName</td>
                    <td>
                        <button @onclick="(() => GetDetail(item.UserId)) "> Click</button>
                    </td>
                </tr>
            }
maxwell
  • 3,254
  • 6
  • 24
  • 39
sami ullah
  • 726
  • 7
  • 13