【问题标题】:Displaying enum Display Name when iterating over enum values in Razor page (in ASP.NET Core)在 Razor 页面中迭代枚举值时显示枚举显示名称(在 ASP.NET Core 中)
【发布时间】: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


【解决方案1】:

如果您有兴趣将枚举绑定到控件或字段,并让系统显示枚举的名称而不是基础值,那么有更好的方法来创建您正在寻找的内容。使这件事变得复杂的重要一点是,在后台,system isn't handlingenum 作为 string 是从开发人员定义的列表中挑选出来的;相反,它默认处理为Int32

我在 Stack Overflow 上找到了一些其他答案,可能会帮助您找到一些更好的可能解决方案。 This answer 解释了如何创建自己的类型安全类,该类像枚举一样处理,但返回您正在寻找的字符串值。 This answer 可能是同一问题的重复,但为该主题添加了更多观点。我使用第一个问题中的代码示例来帮助您了解可以找到您要查找的内容,但可能并不简单。

public class Survey
{
    [Display(Name = "Have you ever been told by a medical professional not to take hormones?")]
    public AnswerYND? ToldNotToTakeHormones { get; set; }
}

public enum AnswerYND
{
    Yes = 1,
    No = 2,
    [Display(Name = "Don't Know")]
    DontKnow = 3
}

class Program
{
    static void Main(string[] args)
    {
        var survey = new Survey();
        Console.WriteLine(survey);
        var options = Enum.GetValues(typeof(AnswerYND));
        for (int i = 0; i < options.Length; i++)
        {
            Console.WriteLine($"Option {i + 1}: {options.GetValue(i)}");
        }
        var choice = Console.ReadLine();
        if (int.TryParse(choice, out int intChoice) && Enum.IsDefined(typeof(AnswerYND), intChoice))
        {
            AnswerYND enumChoice = (AnswerYND)intChoice;
            var name = (enumChoice
                .GetType()
                .GetField(enumChoice.ToString())
                .GetCustomAttributes(typeof(DisplayAttribute), false)
                as DisplayAttribute[])
                .FirstOrDefault()?
                .Name;
            Console.WriteLine($"You selected: {name}");
        }
    }

【讨论】:

    【解决方案2】:

    因此,我能够使用描述而不是显示名称并达到预期的效果。
    我必须创建以下扩展方法:

    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;
        }
    }
    

    然后我可以通过转换Enum.GetValues(typeof(AnswerYND))的结果来访问Razor页面中的扩展方法:

    <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>
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 2020-04-08
      • 2022-10-03
      • 1970-01-01
      相关资源
      最近更新 更多