Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

for loop only render last value #15633

Closed
lakani opened this issue Sep 9, 2018 · 4 comments
Closed

for loop only render last value #15633

lakani opened this issue Sep 9, 2018 · 4 comments
Labels
area-blazor Includes: Blazor, Razor Components

Comments

@lakani
Copy link

lakani commented Sep 9, 2018

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 ?

@lakani
Copy link
Author

lakani commented Sep 9, 2018

Counter.zip

@Andrzej-W
Copy link

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.

@danroth27
Copy link
Member

@Andrzej-W Thanks for answering!

@arivera12
Copy link

arivera12 commented Jan 5, 2019

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

@mkArtakMSFT mkArtakMSFT transferred this issue from dotnet/blazor Oct 27, 2019
@mkArtakMSFT mkArtakMSFT added the area-blazor Includes: Blazor, Razor Components label Oct 27, 2019
@ghost ghost locked as resolved and limited conversation to collaborators Dec 3, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-blazor Includes: Blazor, Razor Components
Projects
None yet
Development

No branches or pull requests

5 participants