Get display annotation value on mvc3 server side code

后端 未结 2 1161
南方客
南方客 2021-01-14 13:17

Is there a way to get the value of an annotation in server side code? For example, I have:

public class Dummy
{
    [Display(Name = \"Foo\")]
    public stri         


        
2条回答
  •  春和景丽
    2021-01-14 13:52

    You will need to use reflection. Here is a sample console program that does what you want.

    class Program
    {
        static void Main(string[] args)
        {
            Dummy dummy = new Dummy();
            PropertyInfo[] properties = dummy.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                IEnumerable displayAttributes = property.GetCustomAttributes(typeof(DisplayAttribute), false).Cast();
                foreach (DisplayAttribute displayAttribute in displayAttributes)
                {
                    Console.WriteLine("Property {0} has display name {1}", property.Name, displayAttribute.Name);
                }
            }
            Console.ReadLine();
        }
    }
    
    public class Dummy
    {
        [Display(Name = "Foo")]
        public string foo { get; set; }
    
        [Display(Name = "Bar")]
        public string bar { get; set; }
    }
    

    This would produce the following result:

    http://www.codetunnel.com/content/images/reflectresult.jpg

提交回复
热议问题