In Blazor (Razor components), is there a way to bind a page url parameter to an enum using the string value of the enum
@page "/index/{MyEnum}"
[Parameter]
public MyEnumType MyEnum { get; set; }
This seems to work while using the integer value of the enum, but it fails to cast the value if using the string.
@page "/index/{MyEnum:int}"
[Parameter]
public MyEnumType MyEnum { get; set; }
Is there a way to make it work with the string?
I've tried using [JsonConverter(typeof(JsonStringEnumConverter))] and [EnumMember(Value = "myVal")] but no luck.
The only solution I have found so far is to bind to a string parameter and convert to enum using Enum.TryParse
@page "/index/{MyEnumString}"
private MyEnumType MyEnum { get; set; }
[Parameter]
public string MyEnumString 
{ 
    get => MyEnum.ToString();
    set
    {
        if (Enum.TryParse<MyEnumType>(value, true, out var enumValue))
        {
            MyEnum = enumValue;
        }
    }
}
The getter is useful if you intend to bind the value to other components.
This can be reduced to:
private MyEnumType MyEnum { get; set; }
[Parameter]
public string MyEnumString 
{ 
    get => MyEnum.ToString();
    set
    {
        Enum.TryParse<MyEnumType>(value, true, out MyEnum);
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With