Reputation: 17654
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
.
Upvotes: 8
Views: 18381
Reputation: 181
@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>
Upvotes: 0
Reputation: 1097
So in short it's like this:
<InputSelect @bind-Value="@YourEnum">
@foreach (var value in Enum.GetValues<YourEnumType>()) {
<option value="@value">@value</option>
}
</InputSelect>
Upvotes: 7
Reputation: 342
<select>
@foreach (var Item in Enum.GetValues(typeof( DayOfWeek)))
{
<option value="@Item">@Item</option>
}
Upvotes: 3
Reputation: 45626
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...
Upvotes: 22