“Display Name” Data Annotation for class using c#

荒凉一梦 提交于 2019-12-03 15:19:56

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
}

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)

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);

Based on @amirhossein-mehrvarzi I have used this function:

public static string GetDisplayName(this object model, string expression)
{
    return ModelMetadata.FromStringExpression(expression, new ViewDataDictionary(model)).DisplayName ?? expression;
}

And used that in this example:

var test = new MyObject();

foreach (var item in test.GetType().GetProperties())
{
        var temp = test.GetDisplayName(item.Name)
}

So many options :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!