Blazor onclick event passing in counter from loop
Because i
is a variable and the for loop is always finished when you click, it is 7 on that moment
You need to do something like:
@for (int i = 0; i < vm.TotalPages; i++)
{
var tempint = i;
<button id="pg-button-@i" class="btn btn-primary btn-sm" type="button"
onclick="@(() => GetTablePage(tempint))">@i</button>
}
This is a standard C# behavior where the lambda expression @(() => GetTablePage(i)) has access to a variable and not to the value of the variable, the result of which is that the lambda expression always calls GetTablePage(i) and i equals 7 at the end of the loop. To solve this you can define a variable scoped locally to the loop like the following:
@for (int i = 0; i < vm.TotalPages; i++)
{
var temp = i;
<button id="pg-button-@temp " class="btn btn-primary btn-sm" type="button"
onclick="@(() => GetTablePage(temp ))">@temp </button>
}
Hope this helps...