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;
}
}