Calling function from generated button in Blazor

I guess you should add a local variable to your loop as follows:

@for (int i = 0; i < Buttons.Count; i++)
    {
        var local = i;
        <button type="button" class="btn btn-primary btn-lg" style="margin:10px" onclick="@((ui) => ButtonClicked(local))">@Buttons[i]</button>
    }

This is a standard C# behavior, not related to Blazor, where the lambda expression @((ui) => ButtonClicked(i)) has access to a variable and not to its value. You’ve got to define a variable which is local to your loop, otherwise your lambda expression always calls ButtonClicked(i) and i equals 3 when the loop ends.

Hope this helps…

Leave a Comment