How to get the Display Name Attribute of an Enum member via MVC Razor code?
UPDATE
First solution was focused on getting display names from enum. Code below should be exact solution for your problem.
You can use this helper class for enums:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
public static class EnumHelper<T>
where T : struct, Enum // This constraint requires C# 7.3 or later.
{
public static IList<T> GetValues(Enum value)
{
var enumValues = new List<T>();
foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
{
enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));
}
return enumValues;
}
public static T Parse(string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static IList<string> GetNames(Enum value)
{
return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();
}
public static IList<string> GetDisplayValues(Enum value)
{
return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();
}
private static string lookupResource(Type resourceManagerProvider, string resourceKey)
{
var resourceKeyProperty = resourceManagerProvider.GetProperty(resourceKey,
BindingFlags.Static | BindingFlags.Public, null, typeof(string),
new Type[0], null);
if (resourceKeyProperty != null)
{
return (string)resourceKeyProperty.GetMethod.Invoke(null, null);
}
return resourceKey; // Fallback with the key name
}
public static string GetDisplayValue(T value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(DisplayAttribute), false) as DisplayAttribute[];
if (descriptionAttributes[0].ResourceType != null)
return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);
if (descriptionAttributes == null) return string.Empty;
return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}
}
And then you can use it in your view as following:
<ul>
@foreach (var value in @EnumHelper<UserPromotion>.GetValues(UserPromotion.None))
{
if (value == Model.JobSeeker.Promotion)
{
var description = EnumHelper<UserPromotion>.GetDisplayValue(value);
<li>@Html.DisplayFor(e => description )</li>
}
}
</ul>
Hope it helps! :)
cant get Enum Display Name property in razor view
like this:
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enumValue)
{
return enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.GetName();
}
}
& the view :
@Model.LectureGig.Gender.GetDisplayName()
Get list of display names from enum c#
Wrote a method quickly, which you can expand from there.
To Use
SourceFromEnum test = new SourceFromEnum();
var me =GetDisplayNames(test);
The Method
public List<string> GetDisplayNames(Enum enm)
{
var type=enm.GetType();
var displaynames = new List<string>();
var names = Enum.GetNames(type);
foreach (var name in names)
{
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DisplayAttribute), true);
if (fds.Length==0)
{
displaynames.Add(name);
}
foreach (DisplayAttribute fd in fds)
{
displaynames.Add(fd.Name);
}
}
return displaynames;
}
can make it static,error checking, etc.
Displaying enum Display Name when iterating over enum values in Razor page (in ASP.NET Core)
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>
}
How do I get the display name attribute for an enumerable on an index page
Here is a demo to get display name with enum value:
EnumExtensions:
public static class EnumExtensions
{
public static string DisplayName(this Enum value)
{
Type enumType = value.GetType();
var enumValue = Enum.GetName(enumType, value);
MemberInfo member = enumType.GetMember(enumValue)[0];
var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
var outString = ((DisplayAttribute)attrs[0]).Name;
if (((DisplayAttribute)attrs[0]).ResourceType != null)
{
outString = ((DisplayAttribute)attrs[0]).GetName();
}
return outString;
}
}
View:
@EnumExtensions.DisplayName(UserStatus._x)
@EnumExtensions.DisplayName(UserStatus._y)
@EnumExtensions.DisplayName(UserStatus._z)
result:
Update:
View:
@foreach (UserStatus userStatus in (UserStatus[])Enum.GetValues(typeof(UserStatus)))
{
@EnumExtensions.DisplayName(userStatus)
}
result:
How to get enum's Display name from integer
string GetEnumDisplayName<T>(T value) where T : Enum
{
var fieldName = Enum.GetName(typeof(T), value);
var displayAttr = typeof(T)
.GetField(fieldName)
.GetCustomAttribute<DisplayAttribute>();
return displayAttr?.Name ?? fieldName;
}
Then invoke it like:
var displayName = GetEnumDisplayName(StateEnum.AmericanSamoa);
EDIT If Timelineinfo.State
is an integer, you can use invoke:
var displayName = GetEnumDisplayName((StateEnum)Timelineinfo.State);
How to get the Display Name Attribute of an Enum member via MVC Razor code?
UPDATE
First solution was focused on getting display names from enum. Code below should be exact solution for your problem.
You can use this helper class for enums:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
public static class EnumHelper<T>
where T : struct, Enum // This constraint requires C# 7.3 or later.
{
public static IList<T> GetValues(Enum value)
{
var enumValues = new List<T>();
foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
{
enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));
}
return enumValues;
}
public static T Parse(string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static IList<string> GetNames(Enum value)
{
return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();
}
public static IList<string> GetDisplayValues(Enum value)
{
return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();
}
private static string lookupResource(Type resourceManagerProvider, string resourceKey)
{
var resourceKeyProperty = resourceManagerProvider.GetProperty(resourceKey,
BindingFlags.Static | BindingFlags.Public, null, typeof(string),
new Type[0], null);
if (resourceKeyProperty != null)
{
return (string)resourceKeyProperty.GetMethod.Invoke(null, null);
}
return resourceKey; // Fallback with the key name
}
public static string GetDisplayValue(T value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(DisplayAttribute), false) as DisplayAttribute[];
if (descriptionAttributes[0].ResourceType != null)
return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);
if (descriptionAttributes == null) return string.Empty;
return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}
}
And then you can use it in your view as following:
<ul>
@foreach (var value in @EnumHelper<UserPromotion>.GetValues(UserPromotion.None))
{
if (value == Model.JobSeeker.Promotion)
{
var description = EnumHelper<UserPromotion>.GetDisplayValue(value);
<li>@Html.DisplayFor(e => description )</li>
}
}
</ul>
Hope it helps! :)
Displaying the full name with Enums and resource file in c# MVC
Try this. It is fairly hacky but it should hopefully give you what you need. I use Assembly.GetExecutingAssembly().GetManifestResourceNames()
to get the names of all the resources in the executing assembly and then I attempt to match the file up correctly using some linq. If it finds a file that looks ok, a new ResourceManager
is created as you were using in your original code.
/// <summary>
/// A generic extension method that aids in reflecting
/// and retrieving any attribute that is applied to an `Enum`.
/// </summary>
public static string GetDisplayName(this Enum enumValue)
{
var displayAttrib = enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>();
var name = displayAttrib.Name;
if (String.IsNullOrEmpty(name))
{
return enumValue.ToString();
}
else
{
var resource = displayAttrib.ResourceType;
if (resource != null)
{
var resources = Assembly.GetExecutingAssembly().GetManifestResourceNames()
.Where(x => x.EndsWith(String.Format("{0}.resources", resource.Name)))
.Select(x => x.Replace(".resources", string.Empty)).ToList();
if (resources.Any())
{
return new ResourceManager(resources.First(), Assembly.GetExecutingAssembly()).GetString(name);
}
}
return name;
}
}
Display a custom text for enum dropdown list in MVC
Try the following:
@Html.DropDownList("enumlist1", Enum.GetValues(typeof(TimeSlots))
.Cast<TimeSlots>()
.Select(e => new SelectListItem() { Value = e.ToString(), Text = e.GetDisplayName() }))
The code above uses the following extension method:
public static class EnumExtensions
{
public static string GetDisplayName(this Enum value)
{
return value.GetType()
.GetMember(value.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
?.GetName();
}
}
The created drop-down list looks like below:
Related Topics
How to Reference Assemblies Using Visual Studio Code
How to Save/Download Pdf Embedded in Web Page Without a Pdf Filename
How to Generate Getters and Setters in Visual Studio
C# How to Check If a Url Exists/Is Valid
Data Binding in MVC 5 and Select2 Multiple Values With Razor Engine
Check If Combobox Value Is Empty
Restsharp Post Request - Body With X-Www-Form-Urlencoded Values
Deserialize Json Array to C# List Object
Easiest Way to Check If an Arbitrary String Is a Valid Filename
How to Provide Success Messages ASP.NET MVC
How to Create a 2D Array from a CSV File
How to Get Total Amount of Ram the Computer Has
Get File Name from Byte Array or Stream
How to Automatically Increment Numbers in C#