I made a simple razor component that just renders a list of strings in buttons. Each button is clickable so when I click one, I add the text "AddedText" to the string inside the button.
This doesn't work since the counter variable always sets to the last position, throwing an out of range exception.
This seems to happen only in the onclick binding, because the list renders correctly in html.
@page "/counter"
@for (int c=0;c<stringlist.Count;c++)
{
<button onclick=@(()=>addText(c))>
@stringlist[c]
</button>
}
```c#
@functions {
List
void addText(int index)
{
stringlist[index] += "AddedText";
}
protected override void OnInit()
{
stringlist.Add("STRING1");
stringlist.Add("STRING2");
stringlist.Add("STRING3");
base.OnInit();
}
}
### Expected behavior
I expected the button when clicked, to change the string in the correct position of the List<string>.
### FIX
To circumvent this issue, I've found that if I use an intermediate counter variable in the FOR LOOP it works, so here's the FOR LOOP change:
```html
@for (int c=0;c<stringlist.Count;c++)
{
int c2 = c; //Intermediate counter
<button onclick=@(()=>addText(c2))>
@stringlist[c2]
</button>
}
This way the loop not only renders correctly, but reacts correctly to the click event modifying the string in the List.
Sorry about the code formatting, I'm new here, haven't found a way to make it more readable.
@chrdlx It's Github Flavored Markdown.
Or you can use the toolbar above the textbox where the <> are.
@chrdlx Congrats on your first issue.
This appears to be a duplicate of aspnet/Blazor#764.
My understanding is that in C# for loops the same variable is reused (so all your lambda functions reference the length of your list).
In your workaround you are declaring a new variable each iteration which is the way C# requires lambdas to be written.
@chrdlx simple introduction to code formatting
https://github.com/aspnet/Blazor/issues/969
@Andrzej-W Thank you!! I changed the description of the issue, now looks better!, also I've found in your posts that this isn't a bug per se, but how C# behaves in these scenarios with binding and lambdas. Now I don't know how to proceed here, I guess someone will set this as "Not a bug".
Thanks again, regards!
Assuming you agree that this is not a bug, you should be able to close it
yourself.
Even though there is probably nothing to fix here, you brought some
attention to a confusing C# feature and it's relation to Blazor, and
hopefully made the solution more searchable. So thanks for your
contribution!
Hopefully this behaviour will be documented soon:
https://github.com/aspnet/Blazor.Docs/issues/371
I have created a few helpful examples in this issue - you can take a look.
As @dmorrison42 said you can close this issue yourself. You should see the Close issue button to the left of the green Comment button.