blazor variable argument passing to onclick function

后端 未结 2 676
轮回少年
轮回少年 2020-12-12 02:22

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

相关标签:
2条回答
  • 2020-12-12 02:50

    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>
    }
    
    0 讨论(0)
  • 2020-12-12 03:02

    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>
                }
    
    0 讨论(0)
提交回复
热议问题