dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.

Home Page:https://asp.net

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Blazor] Actions in for loop, i always at end loop value

Bisjob opened this issue · comments

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Let's make a simple example to be clearer than text.

@for (int i = 0; i < 10; i++)
{
   <button @onclick=@(() => OnClick(i))>@i</button>
}

The OnClick method will always recieve 10 (the end loop value), no matter which button is clicked.

I've found a workaround by storing the value in a local variable :

@for (int i = 0; i < 10; i++)
{
   var curValue = i;
   <button @onclick=@(() => OnClick(curValue))>@i</button>
}

I think we shouldn't take care of storing the loop variable in a local variable.

PS : Couln't find an explicit title

Expected Behavior

No response

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

NET6

Anything else?

No response

@Rizov74 thanks for contacting us.

You need to use a foreach loop or capture the index variable inside the loop.

The issue is that the scope of the for loop variable expands the loop contents and when you use constructs that translate into delegates (like render fragments) that causes the loop variable to be captured. To prevent that from happening, you need to do something like this:

for(var i = 0; i < 10; i++)
{
  var index = i;
}

And use index within the rest of your code.

It is an unfortunate behavior of the interaction between Blazor and the C# compiler, but it is not something we plan to change, as Blazor never transforms the code the user generates (it only transpiles it to C#)