Razor @page enum parameter

165 Views Asked by At

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.

1

There are 1 best solutions below

0
iCollect.it Ltd On

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.