Select box is blank after an option is selected

Viewed 46

I have an Html select box in my Blazor form where a user may select a grade from a GradesTable. However when the user picks an option, the select box rectangle goes into a blank state. I have tried to use a selected in the <option> tag but the box then locks onto the last option when a selection is made. Is there anyway to show the selected option in the box?

<label for="Grade">Choose a Grade:</label>
<select Name="Grade" id="Grade" @bind="selectedGrade">
    <option value="">---No Grade---</option>
    @foreach (var item in grade)
    {
        <option value="@item.Id" selected>@item.GradeDescription</option>
    }
</select>

@code{
   private int? selectedGrade;
    private List<GradeTable> FilteredGrades => selectedGrade.HasValue ?
    grades.Where(s => s.Grade==selectedGrade.Value).ToList() :
    grades;
}
1 Answers

You aren't setting the selected attribute correctly: selected=@"selectedGrade == item.Id"

true will render the attribute, and false will not.

Do this:

<label for="Grade">Choose a Grade:</label>
<select Name="Grade" id="Grade" @bind="selectedGrade">
    <option value="">---No Grade---</option>
    @foreach (var item in grade)
    {
        <option value="@item.Id" selected=@"selectedGrade == item.Id">@item.GradeDescription</option>
    }
</select>

@code {
    private int? selectedGrade;
}
Related