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

后端 未结 8 1711
猫巷女王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<TModel, TProperty>(
          this TModel model
        , Expression<Func<TModel, TProperty>> expression)
    {
        return ModelMetadata.FromLambdaExpression<TModel, TProperty>(
            expression,
            new ViewDataDictionary<TModel>(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!"
    
    0 讨论(0)
  • 2020-12-02 09:11

    Another code snippet with code .Net uses itself to perform this

    public static class WebModelExtensions
    {
        public static string GetDisplayName<TModel, TProperty>(
          this HtmlHelper<TModel> html, 
          Expression<Func<TModel, TProperty>> expression)
        {
            // Taken from LabelExtensions
            var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    
            string displayName = metadata.DisplayName;
            if (displayName == null)
            {
                string propertyName = metadata.PropertyName;
                if (propertyName == null)
                {
                    var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
                    displayName = ((IEnumerable<string>) htmlFieldName.Split('.')).Last<string>();
                }
                else
                    displayName = propertyName;
            }
    
            return displayName;
        }
    }
    // Usage
    Html.GetDisplayName(model => model.Password)
    
    0 讨论(0)
提交回复
热议问题