using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Web; namespace Helper { /// /// This classs contain property releted method /// public static class DisplayNameHelper { /// /// This mehtod is used for get display name of class object property /// /// Represent object of object class contain proerties /// Represent name of the property /// public static string GetDisplayName(object obj, string propertyName) { if (obj == null) return null; return GetDisplayName(obj.GetType(), propertyName); } /// /// This method is used for returns value of display name. /// /// Type of the property /// Represent name of the property /// string public static string GetDisplayName(Type type, string propertyName) { var property = type.GetProperty(propertyName); if (property == null) return null; return GetDisplayName(property); } /// /// This action gives display name of given property of model /// /// PropertyInfo: array of properties informaion /// string public static string GetDisplayName(PropertyInfo property) { // return attribute Display Name of given property. var attrName = GetAttributeDisplayName(property); if (!string.IsNullOrEmpty(attrName)) return attrName; var metaName = GetMetaDisplayName(property); if (!string.IsNullOrEmpty(metaName)) return metaName; return property.Name.ToString(); } /// /// Returns property "DisplayAttribute" value. /// /// /// string private static string GetAttributeDisplayName(PropertyInfo property) { foreach (var item in property.CustomAttributes) { if (item.AttributeType.Name.Equals("DisplayAttribute")) { return item.NamedArguments[0].TypedValue.Value.ToString(); } } return null; } //private static string GetAttributeDisplayName(PropertyInfo property) //{ // var atts = property.GetCustomAttributes( // typeof(DisplayNameAttribute), true); // if (atts.Length == 0) // return null; // return (atts[0] as DisplayNameAttribute).DisplayName; //} /// /// Returns mata data of attribute DisplayName. /// /// PropertyInfo of property /// string private static string GetMetaDisplayName(PropertyInfo property) { var atts = property.DeclaringType.GetCustomAttributes( typeof(MetadataTypeAttribute), true); if (atts.Length == 0) return null; var metaAttr = atts[0] as MetadataTypeAttribute; var metaProperty = metaAttr.MetadataClassType.GetProperty(property.Name); if (metaProperty == null) return null; return GetAttributeDisplayName(metaProperty); } } }