Aspnetcore: for loop only render last value

Created on 9 Sep 2018  路  4Comments  路  Source: dotnet/aspnetcore

i've modified a littel the counter page to try how i can render array of buttons, but i got a strange behavior
@page "/counter"

Counter

`

<p>Current count: @currentCount</p>

<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>

<button class="btn btn-primary" onclick="@Reset">Reset</button>

@for (int i = 0; i < _Sarr.Length; i++) {
<button class="btn btn-primary" onclick="@(e => bReset( i ))">@_Sarr[i]</button>
}

@functions {
int currentCount = 0;

string[] _Sarr = new string[] { "one", "two", "three" };

void IncrementCount()
{
    currentCount++;
}

void bReset(int s)
{
    Console.WriteLine(s.ToString());
    currentCount += s;


}

void Reset()
{
    currentCount = 0;
}

}
`

but whenever i click on one of the buttons in the array , s variable passed by 3

am i doing someting wrong ?

area-blazor

Most helpful comment

Change your loop to something similar to this:

@for (int i = 0; i < _Sarr.Length; i++) {
var local_i = i;
<button class="btn btn-primary" onclick="@(e => bReset( local_i ))">@_Sarr[local_i]</button>
}

This is standard C# behaviour where lambda expression @(e => bReset( local_i )) has access to variable and not to the value of the variable. You have to have variable which is local in for loop, otherwise your lambda expression always calls bReset(i) and i is equal 3 at the end of the loop.

All 4 comments

Change your loop to something similar to this:

@for (int i = 0; i < _Sarr.Length; i++) {
var local_i = i;
<button class="btn btn-primary" onclick="@(e => bReset( local_i ))">@_Sarr[local_i]</button>
}

This is standard C# behaviour where lambda expression @(e => bReset( local_i )) has access to variable and not to the value of the variable. You have to have variable which is local in for loop, otherwise your lambda expression always calls bReset(i) and i is equal 3 at the end of the loop.

@Andrzej-W Thanks for answering!

@Andrzej-W This worked for me as well thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Trcx528 picture Trcx528  路  85Comments

natemcmaster picture natemcmaster  路  213Comments

davidfowl picture davidfowl  路  126Comments

moodya picture moodya  路  153Comments

kevinchalet picture kevinchalet  路  761Comments