Raymond Wong
Raymond Wong

Reputation: 312

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

Upvotes: 8

Views: 6946

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273294

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 =>.

Upvotes: 22

Ibrahim Timimi
Ibrahim Timimi

Reputation: 3710

If you want to use foreach loop instead, you can refer to the example below.

You declare a variable called index inside the loop which is used to store the index of the current item in the loop using the IndexOf method on the items list. This index is then passed as an argument to the clickItem function when the button is clicked.

@foreach (var item in items)
{
    var index = items.IndexOf(item);
    <li> item @item 
        <button onclick=@(() => clickItem(index))>Click</button>
    </li>
}

Upvotes: 0

sami ullah
sami ullah

Reputation: 1094

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>
            }

Upvotes: 0

Related Questions