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

后端 未结 8 1772
猫巷女王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 09:04

    Late to the game, but...

    I created a helper method using ModelMetadata like @Daniel mentioned and I thought I'd share it:

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

    Example Usage:

    Models:

    public class MySubObject
    {
        [DisplayName("Sub-Awesome!")]
        public string Sub { get; set; }
    }
    
    public class MyObject
    {
        [DisplayName("Awesome!")]
        public MySubObject Prop { get; set; }
    }
    

    Use:

    HelperNamespace.GetDisplayName(Model, m => m.Prop) // "Awesome!"
    HelperNamespace.GetDisplayName(Model, m => m.Prop.Sub) // "Sub-Awesome!"
    

提交回复
热议问题