Search K
Appearance
With an EnumField<TEntity, TEnum>
you can represent values from enums in your resource. An enum is useful for fields where you want to limit user choice to a predetermined set of values.
An EnumField<TEntity, TEnum>
is created with two generic type arguments:
TEntity
argument must be a reference type that refers to the underlying entity of the resource.TEnum
argument must be a subtype of Enum
.In our demo application, we use an enum to store an employee's work model. Here's the enum definition.
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum WorkModels {
'OnSite',
'Hybrid',
'Remote'
}
INFO
Enums are typically displayed as numeric indices. To display values as strings, you can add a [JsonConverter(typeof(JsonStringEnumConverter))]
as attribute above the enum definition.
The enum is used in the employee model class.
public class Employee
{
[Key]
public int Id { get; init; }
[Required]
public WorkModels WorkModel { get; set; }
}
You can represent the property in the employee resource by adding it to the list of available fields:
public override IList<IResourceFieldBuilder> Fields()
{
return
[
EnumField<Employee, WorkModels>
.Make("Work Model", nameof(Employee.WorkModel)),
];
}
An EnumField
displays either the numeric index of its value or its text representation, depending on whether you've configured a string enum converter.
In Create and Update views, a user will see a dropdown select. If you have configured a string converter, the member names will be shown as values. Otherwise, a user will see indices of the enum members.
The default visibility values are as follows:
Resource View | Default |
---|---|
Index | visible |
Create | visible |
Update | visible |
Details | visible |
You can change the visibility of the field for each view. Please note, however, that fields should remain visible on Create pages if the field is required by the entity model and if no default value is set.
An EnumField
can be made sortable by chaining a call to Sortable()
after adding the field. Sorting will be performed in alphanumeric order, results will therefore depend on your database provider's enum representation.
public override IList<IResourceFieldBuilder> Fields()
{
return
[
EnumField<Employee, WorkModels>
.Make("Work Model", nameof(Employee.WorkModel))
.Sortable(),
];
}
We provide a default filter for enum fields. Simply chain a Filterable()
method call after the field definition. The filter will consider all available enum values and present them as filter options in a dropdown menu for the user to choose from.
public override IList<IResourceFieldBuilder> Fields()
{
return
[
EnumField<Employee, WorkModels>
.Make("Work Model", nameof(Employee.WorkModel))
.Filterable(),
];
}