1

So if I run the following code in my Blazor WASM application with MudBlazor.

<MudSelect T="int?" @bind-Value="_registerProfileViewModel.DayOfBirth" Label="Day:" Variant="Variant.Outlined">
    @for (var day = 1; day <= 31; day++)
    {
        <MudSelectItem T="int?" Value="@day">@day</MudSelectItem>
    }
</MudSelect>

I get a select box with 31 options that are all 32. I am not sure what I am doing wrong.

EDIT I can do the following, but I want to make sure I am not doing something incorrectly.

<MudSelect T="int?" @bind-Value="_registerProfileViewModel.DayOfBirth" Label="Day:" Variant="Variant.Outlined">
    @for (var day = 1; day <= 31; day++)
    {
        var number = day;
        <MudSelectItem T="int?" Value="@number">@number</MudSelectItem>
    }
</MudSelect>
baynezy
  • 6,493
  • 10
  • 48
  • 73
  • [Kristoffer's answer](https://stackoverflow.com/a/76922747/11779494) and your edit. _This is the way_ . More answers https://stackoverflow.com/a/54813295 – RBee Aug 18 '23 at 15:32

1 Answers1

2

You use a variable day that is later updated (once for each iteration of the loop). To fix this add a local variable inside the loop and use that instead.

<MudSelect T="int?" @bind-Value="_registerProfileViewModel.DayOfBirth" Label="Day:" Variant="Variant.Outlined">
@for (var day = 1; day <= 31; day++)
{
    var localDay = day;
    <MudSelectItem T="int?" Value="@localDay">@localDay</MudSelectItem>
}