I have a property in my class that I can set to an enum value, the enum has the flag attribute. I want to display the Display name of the enum in my view, it works when I've set the Person.Types
to a single value but not when it's set to multiple values.
[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();
I've used this helper method to get the DisplayNameAttribute when the person only have one type. But when the person have two (eg teacher and student) I get an InvalidOperationException: Sequence contains no elements
on enumValue.GetType()
public static string GetDisplayName(this Enum enumValue)
{
return enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.GetName();
}
Then in razor view:
@foreach (var person in Model)
{
<h3>@person.Name<h3>
<p>@person.Types</p>
}
What I expect as an output from person.Types.GetDisplayName()
is "Lärare, Student" instead of "Teacher, Student" as I get from just person.Types
.
I'm using .NET Core.