Generally, we are using lambda expressions to create DOM elements dynamically like in the following code snippet.
<div class="buttons">
@for (int i = 0; i < 5; i++)
{
<button type="button" class="btn btn-primary" onclick="@((e) => ButtonClicked(i))">Button @i</button>
}
</div>
You have to include local variables while rendering the button element to properly get the index value of the clicked button element.
<div class="buttons">
@for (int i = 0; i < 5; i++)
{
var index = i;
<button type="button" class="btn btn-primary" onclick="@((e) => ButtonClicked(index))">Button @i</button>
}
</div>
@code {
private void ButtonClicked(int index)
{
Console.WriteLine("Button clicked with index:" + index);
}
}
Share with