Description
Summary
A new Blazor form component that automatically lists enum values that an InputSelect can receive.
Motivation and goals
I often find myself writing this same InputSelect
code over and over:
<InputSelect @bind-Value="model.SomeEnumVal">
@foreach(var enumVal in Enum.GetValues<SomeEnumVal>())
{
<option value=@enumVal>@enumVal</option>
}
</InputSelect>
A separate InputSelectEnum<TValue>
component that removes this boilerplate could be useful, imo.
// Identical output to above
<InputSelectEnum @bind-Value="model.SomeEnumVal" />
I would write this privately for myself, copying the existing InputSelect code and tweaking it. The only changes from the existing code is a modification of the BuildRenderTree method to generate options instead of displaying child content.
However, certain pieces of the InputSelect
code that I'd use as a baseline are internal
, such as the InputExtensions.TryParseSelectableValueFromString method and InputBase.FieldIdentifier used for value binding and validation messages, respectively.
In scope
- Generating a blazor
select
with all possible enum values - Support for nullable enum as a valid
TValue
- Input parameter for changing how enum values are displayed, in the form of
Func<TValue, string>
. When this parameter is absent, display usingSystem.CompnentModel.DataAnnotations.DisplayAttribute.Name
if available, thenToString()
Out of scope
- Filtering specific enum values from the options
Risks / unknowns
If we wish to support nullable enums, then using the generic constraint where TValue : Enum
is not a valid path. Therefore, type validity will need to be enforced at runtime.
Examples
An existing example of another developer implementing this component can be found here. That particular implementation may have been using the value binding code from this repo as it existed but it now differs from the code we find in main, and thus results in an inconsistent experience alongside the equivalent InputSelect.