Skip to content

Instantly share code, notes, and snippets.

@Xordal
Created September 21, 2016 12:47
Show Gist options
  • Save Xordal/fa148416f9fae69564eeedbcc095c357 to your computer and use it in GitHub Desktop.
Save Xordal/fa148416f9fae69564eeedbcc095c357 to your computer and use it in GitHub Desktop.
Get display name for enum
namespace Model.Enums
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
public static class EnumHelper<T>
{
private static String LookupResource(Type resourceManagerProvider, String resourceKey)
{
foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
{
if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
{
System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
return resourceManager.GetString(resourceKey);
}
}
return resourceKey;
}
public static String GetDisplayValue(T value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DisplayAttribute[] descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(DisplayAttribute), false) as DisplayAttribute[];
if (descriptionAttributes == null) { return String.Empty;}
if (descriptionAttributes[0].ResourceType != null)
return LookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);
return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}
}
}
namespace Model.Enums
{
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Size type.
/// </summary>
public enum SizeType
{
[Display(Name = @"Small")]
Small,
[Display(Name = @"Medium")]
Medium,
[Display(Name = @"Large")]
Large,
[Display(Name = @"X-Large")]
XLarge
}
}
var spaceSizeTypesList = [""];
@foreach (var item in Enum.GetValues(typeof(SizeType)))
{
@:spaceSizeTypesList.push("@(EnumHelper<SizeType>.GetDisplayValue((SizeType) item))");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment