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

后端 未结 8 1819
猫巷女王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:11

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

    public static class WebModelExtensions
    {
        public static string GetDisplayName(
          this HtmlHelper html, 
          Expression> 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) htmlFieldName.Split('.')).Last();
                }
                else
                    displayName = propertyName;
            }
    
            return displayName;
        }
    }
    // Usage
    Html.GetDisplayName(model => model.Password)
    

提交回复
热议问题