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

[Blazor] Bug in the for loop in Razor template #6591

Open
txgz999 opened this Issue Jan 11, 2019 · 6 comments

Comments

Projects
None yet
4 participants
@txgz999
Copy link

txgz999 commented Jan 11, 2019

Describe the bug

Passing variable to event handler inside a for loop behaves unexpectedly

To Reproduce

Using the latest Visual Studio 2017 Version 15.9.5 and the Blazor template, create a page with the following content:
@page "/forloop"
@for(var i=1; i<=2; i++) {
<button onclick="@(()=>showNumber(i))">@i</button>
}
@functions {
void showNumber(int n) {
Console.WriteLine(n);
}
}
When I click either of these two buttons, number 3 is passed to the event handling function.

Expected behavior

I expect when I click the first button, the value passed to the event handler should be 1, and when clicking the second button, the value passed to the handler should be 2.

Screenshots

Additional context

As a comparison, if I replace the for loop with a foreach loop as follows:
@foreach(var i in Enumerable.Range(1,2)) {
<button onclick="@(()=>showNumber(i))">@i</button>
}
then the behavior is expected.

@txgz999

This comment has been minimized.

Copy link

txgz999 commented Jan 11, 2019

1

@txgz999 txgz999 changed the title Bug in the for loop in Razor template [Blazor] Bug in the for loop in Razor template Jan 11, 2019

@barakimam

This comment has been minimized.

Copy link

barakimam commented Jan 11, 2019

@txgz999 Kindly check the generated html code, is the expected argument passed into showNumber?

@ghidello

This comment has been minimized.

Copy link

ghidello commented Jan 11, 2019

In the first example the for loop is assigning the same variable to all the lambdas so, at the end of the loop, all the lambdas will point to the same value. In the second example the enumerator produces a collection of different variables and the loop binds them to the lambdas so they’ll have different values. Try to create a local variable inside the first loop and assign it to the lambda as suggested in this issue: aspnet/Blazor#1402

@txgz999

This comment has been minimized.

Copy link

txgz999 commented Jan 11, 2019

@Eilon Eilon added the area-mvc label Jan 11, 2019

@txgz999

This comment has been minimized.

Copy link

txgz999 commented Jan 11, 2019

@ghidello

This comment has been minimized.

Copy link

ghidello commented Jan 12, 2019

I’m glad it helped!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment