【发布时间】:2021-01-31 11:44:43
【问题描述】:
在 Razor 页面(在 ASP.NET Core 中)上迭代枚举值时,如何显示枚举的显示名称?
剃刀页面:
<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>
}
剃须刀页面背后的代码:
public class EditModel : PageModel
{
[BindProperty]
public Survey Survey { get; set; }
调查类:
public class Survey
{
[Display(Name = "Have you ever been told by a medical professional not to take hormones?")]
public AnswerYND? ToldNotToTakeHormones { get; set; }
回答YND:
public enum AnswerYND
{
Yes,
No,
[Display(Name="Don't Know")]
DontKnow
}
【问题讨论】:
-
我使用的一种方法是创建一个扩展方法来获取枚举的Description 属性。然后,您可以在 for each 循环中使用扩展方法。如果您需要了解如何创建扩展方法,请参阅本文。 blog.hildenco.com/2018/07/…
标签: c# loops asp.net-core enums displayname-attribute