Skip to content

For loop variable scope #15526

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

Closed
rovercoder opened this issue Oct 14, 2018 · 3 comments
Closed

For loop variable scope #15526

rovercoder opened this issue Oct 14, 2018 · 3 comments
Labels
area-blazor Includes: Blazor, Razor Components

Comments

@rovercoder
Copy link

It seems that variables inside for loops are not being scoped correctly. The index per iteration is lost for either bind or onchange, but appears correctly when printed out as HTML. No matter what I do I always get the final index value (PlayerCount = 2 produces an i = 3 for both entries).

image

1. Using onchange method

@for (int i = 1; i <= PlayerCount; i++)
{
    <text>Player </text>@i <input type="text" onchange=@(e => WritePlayerName(i, e)) /><br />
}

@functions{
    [Parameter] int PlayerCount { get; set; } 
    void WritePlayerName(int playerNo, UIChangeEventArgs ev)
    {
        Console.WriteLine(playerNo + " " + ev.Value.ToString());
    }
}

Results

3 Andy
3 John

2. Binding array element

@for (int i = 1; i <= PlayerCount; i++)
{
    <text>Player </text>@i <input type="text" bind=@playerNames[i-1] /><br />
}

@functions{
    [Parameter] int PlayerCount { get; set; }
    string[] playerNames;
    protected override void OnParametersSet()
    {
        playerNames = new string[PlayerCount];
    }
}

image

Am I missing something? Is there a better way?

@Andrzej-W
Copy link

Look at aspnet/Blazor#1402

@rovercoder
Copy link
Author

Can be closed thanks!

@danroth27
Copy link
Member

Thanks @Andrzej-W for answering!

@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

4 participants