How do you display the Display name for an enum when you're iterating over the enum values on a Razor Page (in ASP.NET Core)?
Razor Page:
<label asp-for="Survey.ToldNotToTakeHormones"></label><br />
@foreach (var answer in Enum.GetValues(typeof(AnswerYND)))
{
<div class="custom-control custom-radio custom-control-inline ">
<label><input type="radio" asp-for="Survey.ToldNotToTakeHormones" value="@answer" />@answer</label>
</div>
}
Code behind razor page:
public class EditModel : PageModel
{
[BindProperty]
public Survey Survey { get; set; }
Survey class:
public class Survey
{
[Display(Name = "Have you ever been told by a medical professional not to take hormones?")]
public AnswerYND? ToldNotToTakeHormones { get; set; }
AnswerYND:
public enum AnswerYND
{
Yes,
No,
[Display(Name="Don't Know")]
DontKnow
}
So, I was able to utilize Description instead of Display Name and achieved the desired effect.
I had to create the following extension method:
And then I was able to access the extension method in the Razor page by casting the result of
Enum.GetValues(typeof(AnswerYND))
: