Created
September 21, 2016 12:47
-
-
Save Xordal/fa148416f9fae69564eeedbcc095c357 to your computer and use it in GitHub Desktop.
Get display name for enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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