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:
public static class EnumHelper
{
public static string GetDescription<T>(this T enumValue)
where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
return null;
var description = enumValue.ToString();
var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
if (fieldInfo != null)
{
var attrs = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attrs != null && attrs.Length > 0)
{
description = ((DescriptionAttribute)attrs[0]).Description;
}
}
return description;
}
}
And then I was able to access the extension method in the Razor page by casting the result of Enum.GetValues(typeof(AnswerYND))
:
<label asp-for="Survey.CurrenltyUsingBirthControl"></label><br />
@foreach (var answer in Enum.GetValues(typeof(AnswerYND)).Cast<AnswerYND>())
{
<div class="custom-control custom-radio custom-control-inline ">
<label><input type="radio" asp-for="Survey.CurrenltyUsingBirthControl" value="@answer" />@answer.GetDescription()</label>
</div>
}