I am trying to get the Required attribute to work with InputSelect but validation doesn't work in Blazor Server. The form can be submitted without selection. Interestingly it works when the model property is nullable. Before .NET 5.0 it didn't work with nullable types because the InputSelect didn't support them. I however want a non-nullable required property because I want to reuse the dto from my API as a model and because it is logically wrong.
public class SomeModel
{
[Required]
public string SomeString { get; set; }
[Required]
public SomeEnum SomeEnum { get; set; }
[Required]
public SomeEnum? SomeNullableEnum { get; set; }
[Required]
public int SomeInt { get; set; }
[Required]
public int? SomeNullableInt { get; set; }
}
public enum SomeEnum
{
A = 1,
B = 2
}
The page
@page "/testrequired"
@using TestNET5BlazorServerApp.Data;
<EditForm Model="Model" OnValidSubmit="Submit">
<DataAnnotationsValidator />
<ValidationSummary />
String:
<br />
<InputText @bind-Value="Model.SomeString" />
<br />
<br />
Enum:
<br />
<InputSelect @bind-Value="Model.SomeEnum">
<option value="">Select Enum</option>
<option value="@SomeEnum.A">@SomeEnum.A</option>
<option value="@SomeEnum.B">@SomeEnum.B</option>
</InputSelect>
<br />
<br />
Nullable Enum:
<br />
<InputSelect @bind-Value="Model.SomeNullableEnum">
<option>Select Nullable Enum</option>
<option value="@SomeEnum.A">@SomeEnum.A</option>
<option value="@SomeEnum.B">@SomeEnum.B</option>
</InputSelect>
<br />
<br />
Int:
<br />
<InputSelect @bind-Value="Model.SomeInt">
<option>Select Int</option>
<option value="1">1</option>
<option value="2">2</option>
</InputSelect>
<br />
<br />
Nullable Int:
<br />
<InputSelect @bind-Value="Model.SomeNullableInt">
<option>Select Nullable Int</option>
<option value="1">1</option>
<option value="2">2</option>
</InputSelect>
<br />
<br />
<button type="submit">Save</button>
</EditForm>
@code
{
SomeModel Model = new Data.SomeModel();
void Submit()
{
System.Diagnostics.Debug.WriteLine("Enum " + Model.SomeEnum);
System.Diagnostics.Debug.WriteLine("Nullable Enum " + Model.SomeNullableEnum);
System.Diagnostics.Debug.WriteLine("Int " + Model.SomeInt);
System.Diagnostics.Debug.WriteLine("Nullable Int " + Model.SomeNullableInt);
}
}
