0
votes

I have the following custom InputSelect component that builds a list of enums from the underlying value type and is working.

CustomInputSelectEnum.razor

<select id="@Id" @bind="CurrentValueAsString">
    @foreach (Enum e in Enum.GetValues(EnumType))
    {
        <option value="@e">@EnumExtensions.GetDescription(e)</option>
    }
</select>

@typeparam TValue
@inherits InputBase<TValue>
@using System.Globalization;
@using Shared.Utils;

@code
{
    [Parameter] public string Id { get; set; } = Guid.NewGuid().ToString();
    [Parameter] public bool IsNullable { get; set; }
    protected Type EnumType => IsNullable ? Nullable.GetUnderlyingType(typeof(TValue)) : typeof(TValue);

    protected override bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage)
    {
        if (typeof(TValue).IsEnum || (EnumType?.IsEnum == true))
        {
            var success = BindConverter.TryConvertTo<TValue>(value, CultureInfo.CurrentCulture, out var parsedValue);
            if (success)
            {
                result = parsedValue;
                validationErrorMessage = null;
                return true;
            }
            else
            {
                result = default;
                validationErrorMessage = $"The {FieldIdentifier.FieldName} field is not valid.";
                return false;
            }
        }

        throw new InvalidOperationException($"{GetType()} does not support the type '{typeof(TValue)}'.");

    }
}
<CustomInputSelectEnum @bind-Value="Foo" IsNullable="true" />
public Bar? Foo { get; set; }

So currently, the select options will be built from the enum Bar.

I want to modify CustomInputSelectEnum.razor to have the ability to pass in a different enum to build the select options rather than getting the options from TValue. If this optional/additional enum is specified, it is used, else the enums from TValue are used.

Is this possible?

1

1 Answers

1
votes

I don't think it will be - the point of enums is to be strongly typed so you don't mix them up. So, selecting one value type, out of a list from a different type seems strange to me and I'd reconsider the need for such design.

If you do want to go down this road, I can suggest you look into using integers instead of enums so you can build up lists of whatever you want in the markup, and then raise ValueCanged by parsing that int into the enum you get in TValue.