Reputation: 1190
Let's say that we have a really simple class with 2 properties, one is an integer and the other one is a string. I want to use EditForm with 2 InputSelect elements that are bind to these properties. The code looks like this:
@page "/test"
@using Microsoft.AspNetCore.Components
@using Newtonsoft.Json
<PageTitle>Test</PageTitle>
<h3>Test form</h3>
<EditForm Model="@_dummy" OnValidSubmit="@TestAsync">
<DataAnnotationsValidator/>
<ValidationSummary/>
<div class="mb-3">
<label for="string" class="form-label">String</label>
<InputSelect id="string" @bind-Value="_dummy.StringProp" class="form-select">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</InputSelect>
</div>
<div class="mb-3">
<label for="int" class="form-label">Integer</label>
<InputSelect id="int" @bind-Value="_dummy.IntProp" class="form-select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</InputSelect>
</div>
<button type="submit" class="btn btn-primary">Start</button>
</EditForm>
@code {
readonly Dummy _dummy = new();
private void TestAsync()
{
Console.WriteLine("Object state: " + JsonConvert.SerializeObject(_dummy));
}
class Dummy
{
public string? StringProp { get; set; }
public int IntProp { get; set; }
}
}
Here is how it looks like in a web browser:
Why is the string value selected and the integer value isn't?
When I submit this form without interacting with Select element I will get a null for StringProp. That is not intuitive for users since this option is shown as already selected. If I interact with it then the value will be correct.
Also I tried to use the selected attribute on the Integer Option element and it has no effect. I cannot make any value to be pre-selected.
Am I doing something wrong or is this a bug? I am using .NET 6.0
Upvotes: 0
Views: 1936
Reputation: 30310
The default string value is set to null
. So the Select shows the first value. Note it only shows it in the UI, it doesn't set it on the model object as no change event has occurred.
The int
default value is 0, which is a real number but isn't in the list of options, so nothing is selected because the actual value is not in the list.
You can make the behaviour the same with this:
class Dummy
{
public string StringProp { get; set; } = string.Empty;
public int IntProp { get; set; } = 0;
}
This is the coded default behaviour for InputSelect
. You may not agree with it, but it's no bug.
If you want your model object to have default values, set them on the object. If you want to force the User to select values do data validation.
Upvotes: 2