1

I'm creating an application with Blazor where I like to have a checkbox group. I have a list of options to display and I use a simple for for it

@for (int i = 0; i < Choices?.Count(); i++)
{
        <div class="checkbox-option">
            <input type="checkbox" id="Name" name="Name" value="@(i + 1)"
                   @onchange="eventArgs => { CheckChanged(i, eventArgs.Value); } ">
            <label for="@($"{ElementData.Name}-{i}")">@Choices[i]</label>
        </div>
}

@code {
    void CheckChanged(int index, object checkValue)
    {
        var i = item;
    }
}

I expect in the index variable to have a different value for each option. I was surprised when I started to debug and the parameter index has always the same value and it is the number of Choices.

I can't understand where the problem is.

Update

If I change the code introducing a variable where to store the number i it is working as expected

@for (int i = 0; i < Choices?.Count(); i++)
{
        var rtn = i;
        <div class="checkbox-option">
            <input type="checkbox" id="Name" name="Name" value="@(i + 1)"
                   @onchange="eventArgs => { CheckChanged(rtn, eventArgs.Value); } ">
            <label for="@($"{ElementData.Name}-{i}")">@Choices[i]</label>
        </div>
}

@code {
    void CheckChanged(int index, object checkValue)
    {
        var i = item;
    }
}
Enrico
  • 3,592
  • 6
  • 45
  • 102

1 Answers1

0

You are missing a vital piece of knowledge.

Your code produces a RenderFragment, it doesn't actually render the component. Your component just stacks the RenderFragment onto the Renderer's queue. The Renderer services that queue when it gets thread time and updates the UI.

See this answer (and several others) for an explanation - For loop not returning expected value - C# - Blazor

Normal practice is to do what you've done in your second code block, or just use a foreach.

MrC aka Shaun Curtis
  • 19,075
  • 3
  • 13
  • 31