How to get the column titles from the Display(Name=) DataAnnotation for a strongly typed list scaffold view at runtime?

后端 未结 3 996
深忆病人
深忆病人 2020-12-05 08:29

How do I get the [Display(Name=\"Some Title\")] DataAnnotations \"Some Title\" rendered in the List scaffold view\'s output?

I create a strongly typed l

3条回答
  •  Happy的楠姐
    2020-12-05 08:41

    //MVC4 has the DisplayNameFor Extensions
    
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString DisplayNameFor(this HtmlHelper> helper, Expression> expression)
        {
            return DisplayNameFor(expression);
        }
    
        public static MvcHtmlString DisplayNameFor(this HtmlHelper helper, Expression> expression)
        {
            return DisplayNameFor(expression);
        }
    
        private static MvcHtmlString DisplayNameFor(Expression> expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, new ViewDataDictionary());
            var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string s = metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last());
            return new MvcHtmlString(HttpUtility.HtmlEncode(s));
        }
    }
    

提交回复
热议问题