For ASP.Net Core 3.0, this worked for me (credit to previous answerers).
My Enum class:
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
public class Enums
{
public enum Duration
{
[Display(Name = "1 Hour")]
OneHour,
[Display(Name = "1 Day")]
OneDay
}
// Helper method to display the name of the enum values.
public static string GetDisplayName(Enum value)
{
return value.GetType()?
.GetMember(value.ToString())?.First()?
.GetCustomAttribute<DisplayAttribute>()?
.Name;
}
}
My View Model Class:
public class MyViewModel
{
public Duration Duration { get; set; }
}
An example of a razor view displaying a label and a drop-down list. Notice the drop-down list does not require a helper method:
@model IEnumerable<MyViewModel>
@foreach (var item in Model)
{
<label asp-for="@item.Duration">@Enums.GetDisplayName(item.Duration)</label>
<div class="form-group">
<label asp-for="@item.Duration" class="control-label">Select Duration</label>
<select asp-for="@item.Duration" class="form-control"
asp-items="Html.GetEnumSelectList<Enums.Duration>()">
</select>
</div>
}