How can I use the values of an enum class as options for an InputSelect?
Example enum:
public enum Test
{
Test1,
Test2
}
I am using with Blazor with Razor components.
How can I use the values of an enum class as options for an InputSelect?
Example enum:
public enum Test
{
Test1,
Test2
}
I am using with Blazor with Razor components.
Here's a working sample how to use enum in InputSelect component:
<EditForm EditContext="@EditContext">
<DataAnnotationsValidator />
<div class="form-group">
<label for="name">Enter your Name: </label>
<InputText Id="name" Class="form-control" @bind-Value="@comment.Name"></InputText>
<ValidationMessage For="@(() => comment.Name)" />
</div>
<div class="form-group">
<label for="body">Select your country: </label>
<InputSelect @bind-Value="@comment.Country" >
@foreach (var country in Enum.GetValues(typeof(Country)))
{
<option value="@country">@country</option>
}
</InputSelect>
<ValidationMessage For="@(() => comment.Country)" />
</div>
<p>
<button type="submit">Submit</button>
</p>
</EditForm>
@code
{
private EditContext EditContext;
private Comment comment = new Comment();
protected override void OnInitialized()
{
EditContext = new EditContext(comment);
base.OnInitialized();
}
public enum Country
{
USA = 1,
Britain,
Germany,
Israel
}
public class Comment
{
public string Name { get; set; }
public Country Country { get; set; }
}
}
Hope this helps...
<select>
@foreach (var Item in Enum.GetValues(typeof( DayOfWeek)))
{
<option value="@Item">@Item</option>
}
@enet answer is correct.
To add to this, sometimes enum values won't accept specific chars. you can edit the display of enum value to display specific chars in the code if you have filtered or changed enum values to store correctly. like below in my enum i replace all spaces with underscore. so you can add this to the code to display the enum values on the dropdown correctly.
<InputSelect @bind-Value="@updateUserDetails.Nationality" class="dropDownSelectList">
@foreach (var countryName in Enum.GetValues(typeof(Nationality)))
{
<option value="@countryName">@(@countryName.ToString().Replace("_", " ").Replace("HH", "-"))</option>
}
</InputSelect>