Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor @page enum parameter

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.

like image 534
ZeW Avatar asked Oct 28 '25 05:10

ZeW


1 Answers

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);
    }
}
like image 59
Gone Coding Avatar answered Oct 30 '25 21:10

Gone Coding