1

So, I am using blazor to make an application. In the HTML part of a razor page I am making a table like this:

@for (int index = 1; index < amounts.Count; index++)
{
<table>
<tr>
    <td> @amounts[index] </td>
</tr>
</table>
}

I need to add an @onclick event to each cell, the problem is that de arguments of that function are changing with the for loop.

So that means that if I do it like this (see below). Every cell will do onclick(amounts.Count) (Which is the last index of the table, the last value of index).

@for (int index = 1; index < amounts.Count; index++)
{
<table>
<tr>
    <td @onclick="()=>Redirect(index)"> @amounts[index] </td>
<tr>
</table>
}

I am not sure if I explained this enough and if my question is clear. Please let me know if it is not.

One solution might be that I get the rownumber of the cell. I have tried some things but I can not figure out how to get the rownumber if you make a table like this with a for-function.

1 Answers1

4

You problem is that value of index is gets "captured" in the lambda and when the function is invoked, the value of Index is always the same. Find details here.

Change your code like this:

@for (int index = 1; index < amounts.Count; index++)
{
   int localVal = index;
<table>
<tr>
    <td @onclick="()=>Redirect(localVal)"> @amounts[index] </td>
<tr>
</table>
}

When you introduce a variable in the scope of the loop, the compiler will know to capture the value separately for each iteration of the loop.

Nick
  • 4,787
  • 2
  • 18
  • 24