In my Blazor app, the <InputSelect />
component is not working as expected. The first option is being shown as selected, but when I submit the form it is always null.
Relevant Model properties:
public int? Distance { get; set; }
public Dictionary<int, string> DistanceList { get; set; }
//Set in the constructor
DistanceList = new Dictionary<int, string>()
{
{ 5, "5 Miles" },
{ 10, "10 Miles" },
{ 25, "25 Miles" }
};
Select List:
<InputSelect @bind-Value="model.Distance">
@foreach (var distance in model.DistanceList)
{
<option [email protected]>@distance.Value</option>
}
</InputSelect>
If I select “10 Miles” or “25 Miles” first, then select “5 miles”, then submit the form, Distance will be 5 miles. But if I just submit the form, Distance is null. Even though, 5 miles is selected.
The problem is that null
is not a option in the list, so the select displays the list but nothing is actually selected.
Either set Distance
as not nullable with a default valid value, or do something like this:
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
<InputSelect class="form-select" @bind-Value="Distance">
@if (Distance is null)
{
<option selected disabled value="null"> -- Select A Value -- </option>
}
@foreach (var distance in DistanceList)
{
<option [email protected]>@distance.Value</option>
}
</InputSelect>
<div class="bg-dark text-white m-2 p-2">
<pre>Distance : @Distance</pre>
</div>
@code {
public int? Distance { get; set; }
public Dictionary<int, string> DistanceList = new Dictionary<int, string>()
{
{ 5, "5 Miles" },
{ 10, "10 Miles" },
{ 25, "25 Miles" }
};
}
Which will look like this:
2
Probably because your Distance
is not set yet. So your Distance
is null
, but UI displays options that you populated and it doesn’t have nullable option to match Distance
to it. So it displays incorrectly.
You can fix it the next way:
<InputSelect @bind-Value="model.Distance">
@foreach (var distance in model.DistanceList)
{
@if (model.Distance == null)
{
model.Distance = @distance.Key;
}
<option [email protected]>@distance.Value</option>
}
</InputSelect>
It will help you to avoid creating an empty option and will allow to set the first value in the DistanceList
as selected.