Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Display Name" Data Annotation for class using c#

I have a class with [Display(Name ="name")] set in the properties, and [Table("tableName"] in the top of the class.

Now I'm using reflection to get some information of this class and I'm wondering if somehow I can add a [Display(Name ="name")] to the class itself.

It will be something like

[Table("MyObjectTable")]
[Display(Name ="My Class Name")]     <-------------- New Annotation
public class MyObject
{
   [Required]
   public int Id { get; set; }

   [Display(Name="My Property Name")]
   public string PropertyName{ get; set; }
}
like image 536
estebane97 Avatar asked Jul 24 '13 05:07

estebane97


3 Answers

There is already an attribute for that in .Net: http://msdn.microsoft.com/en-us/library/system.componentmodel.displaynameattribute.aspx . And yes, you can use it on both: properties and classes (check an AttributeUsageAttribute in Syntax section)

like image 43
Nikita B Avatar answered Nov 07 '22 15:11

Nikita B


Based on that article I referenced heres a complete example

Declare Custom Attribute

[System.AttributeUsage(System.AttributeTargets.Class)]
public class Display : System.Attribute
{
    private string _name;

    public Display(string name)
    {
        _name = name;        
    }

    public string GetName()
    {
        return _name;
    }
}

Example of use

[Display("My Class Name")]
public class MyClass
{
    // ...
}

Example of reading attribute

public static string GetDisplayAttributeValue()
{
    System.Attribute[] attrs = 
            System.Attribute.GetCustomAttributes(typeof(MyClass)); 

    foreach (System.Attribute attr in attrs)
    {
        var displayAttribute as Display;
        if (displayAttribute == null)
            continue;
        return displayAttribute.GetName();   
    }

    // throw not found exception or just return string.Empty
}
like image 123
Chris Moutray Avatar answered Nov 07 '22 15:11

Chris Moutray


Simply write a static function like this:

public static string GetDisplayName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> expression)
{
    return ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, new ViewDataDictionary<TModel>(model)).DisplayName;
}

And use that like this:

string name = GetDisplayName(Model, m => m.Prop);
like image 38
Amirhossein Mehrvarzi Avatar answered Nov 07 '22 15:11

Amirhossein Mehrvarzi