0

I think this is a very simple question but I can't find any solution or I think I don't know how to search with such something, so if this question has been asked before please point me to such a duplicate

Suppose I have a class like this:

    public class Company
    {
        public int ID { get; set; }
        public Nullable<int> ApplicationID { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessageResourceType = typeof(MyResource),
                ErrorMessageResourceName = "RequiredCompanyName")]
        [Display(Name = "CompanyName", ResourceType = typeof(MyResource))]
        public string EntityName { get; set; }

        public Nullable<int> EntityID { get; set; }
    }

I want to get the name of the attribute associated with Property EntityName in a razor view. I know it's pretty easy to get the resource string value using DisplayFor html helper, but I need here to get the name of the attribute value associated with the property which in this case is the string "CompanyName". Is this doable ?

Ibrahim Amer
  • 1,147
  • 4
  • 19
  • 46
  • 1
    possible duplicate of [Get \[DisplayName\] attribute of a property in strongly-typed way](http://stackoverflow.com/questions/5474460/get-displayname-attribute-of-a-property-in-strongly-typed-way) – Ehsan Sajjad Sep 17 '15 at 09:26
  • check this as well :http://stackoverflow.com/questions/3885796/get-displayname-attribute-without-using-labelfor-helper-in-asp-net-mvc – Ehsan Sajjad Sep 17 '15 at 09:26

1 Answers1

0

If you want the value of Display attribute in razor, you can also use LabelFor helper. But if your requirement is not to use these helper, you can get the value something like following, and then store in ViewBag for example, or make it part of your model and use it in razor.

You can get the attribute value like this -

        var objCompany = new Company();//Or any other way to get the instance of object.

        var displayAttribute = objCompany .GetType()
         .GetMember("EntityName").First()
         .GetCustomAttributes(typeof(DisplayAttribute), true)
         .GetValue(0);

        var displayAttributeValue = ((DisplayAttribute)(displayAttribute)).Name;

The displayAttributeValue variable will contain the Name value of Display attribute i.e. CompanyName

Yogi
  • 9,174
  • 2
  • 46
  • 61