枚举标记从多个获取displayname

问题描述 投票:0回答:1

我的类中有一个属性,我可以设置为枚举值,枚举有flag属性。我想在我的视图中显示枚举的显示名称,它在我将Person.Types设置为单个值时起作用,但在将其设置为多个值时则不起作用。

[Flags]
public enum TypesEnum
{
    [Display(Name = "Lärare")]
    Teacher = 1,
    [Display(Name = "Student")]
    Student = 2
}

public class Person
{
    public string Name { get; set; }
    public TypesEnum Types { get; set; }
}

person.Types = TypesEnum.Teacher | TypesEnum.Student;

var model = db.Persons
            .Where(x => x.Types.HasFlag(TypesEnum.Teacher))
            .ToList();

当人只有一种类型时,我已经使用了这个帮助方法来获取DisplayNameAttribute。但当这个人有两个(例如老师和学生)时,我会在InvalidOperationException: Sequence contains no elements上获得enumValue.GetType()

public static string GetDisplayName(this Enum enumValue)
{
    return enumValue.GetType()
                    .GetMember(enumValue.ToString())
                    .First()
                    .GetCustomAttribute<DisplayAttribute>()
                    .GetName();
}

然后在剃刀视图中:

@foreach (var person in Model)
{
    <h3>@person.Name<h3>
    <p>@person.Types</p>
}

我期望作为person.Types.GetDisplayName()的输出是“Lärare,学生”而不是“老师,学生”,因为我从person.Types得到。我正在使用.NET Core。

c# asp.net-mvc enums
1个回答
0
投票

以下是使用一些静态助手进行此操作的一种方法:

    /// <summary>
    /// Gets the display name for an enum.
    /// </summary>
    /// <param name="enumValue"></param>
    /// <exception cref="ArgumentException"></exception>
    /// <returns></returns>
    public static string GetDisplayName(this Enum enumValue)
    {
        var enumType = enumValue.GetType();
        var names = new List<string>();
        foreach (var e in Enum.GetValues(enumType))
        {
            var flag = (Enum)e;              
            if(enumValue.HasFlag(flag))
            {
                names.Add(GetSingleDisplayName(flag));
            }
        }
        if (names.Count <= 0) throw new ArgumentException();
        if (names.Count == 1) return names.First();
        return string.Join(",", names);
    }

    /// <summary>
    /// Gets the display value for a single enum flag or 
    /// name of that flag if the display value is not set
    /// </summary>
    /// <param name="flag"></param>
    /// <returns></returns>
    public static string GetSingleDisplayName(this Enum flag)
    {
        try
        {
            return flag.GetType()
                    .GetMember(flag.ToString())
                    .First()
                    .GetCustomAttribute<DisplayAttribute>()
                    .Name;
        }
        catch
        {
            return flag.ToString();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.