Get [DisplayName] attribute of a property in strongly-typed way

后端 未结 8 1771
猫巷女王i
猫巷女王i 2020-12-02 08:43

Good day!

I\'ve such method to get [DisplayName] attribute value of a property (which is attached directly or using [MetadataType] attribut

8条回答
  •  無奈伤痛
    2020-12-02 08:48

    @Buildstarted Answer works but i wanted to get the DisplayName by property name rather using linq expression so i did a little change that will save your time

    public static string GetDisplayNameByMemberName(string memberName)
        {
            Type type = typeof(TModel);
            string propertyName = memberName;
    
            DisplayAttribute attr;
            attr = (DisplayAttribute)type.GetProperty(propertyName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();
    
            //Look for [MetadataType] attribute in type hierarchy
            //http://stackoverflow.com/questions/1910532/attribute-isdefined-doesnt-see-attributes-applied-with-metadatatype-class
            if (attr == null)
                {
                    MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
                    if (metadataType != null)
                    {
                        var property = metadataType.MetadataClassType.GetProperty(propertyName);
                        if (property != null)
                        {
                            attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();
                        }
                    }
                }
            return (attr != null) ? attr.Name : String.Empty;
        }
    

    I also wanted to get the localized value in the resources (.resx files) so :

    string displayName = GeneralHelper.GetDisplayNameByMemberName(memberName);
    string displayNameTranslated = resourceManager.GetString(displayName, MultiLangHelper.CurrentCultureInfo);
    

    This is a helper function i made to return an object of type "CultureInfo", create a culture info of some language or pass the current one

    //MultiLangHelper.CurrentCultureInfo
    return System.Threading.Thread.CurrentThread.CurrentCulture;
    

提交回复
热议问题