Html帮助器显示没有标签的显示名称属性

时间:2012-07-12 08:25:17

标签: c# html asp.net-mvc html-helper

我有这个:

[Display(Name = "Empresa")]
public string Company{ get; set; }

在我的aspx中我有:

<th><%: Html.LabelFor(model => model.Company)%></th>

这会产生:

<th><label for="Company">Empresa</label></th>

是否有任何html帮助扩展只显示没有标签的display属性,只显示纯文本?我想要的输出是:

<th>Empresa</th>

谢谢!

修改

我按照建议尝试了DisplayFor或DisplayTextFor,但它们无效,因为它们生成:

<th>Amazon</th> 

它们返回属性的值...我想要显示属性的名称。

1 个答案:

答案 0 :(得分:12)

延迟修改

在&gt; = MVC4中,只需使用@Html.DisplayNameFor

在此之前

使用您自己的助手

public static MvcHtmlString SimpleLabelFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression
) {
  var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
  string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
  string resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
  if (String.IsNullOrEmpty(resolvedLabelText)) 
            return MvcHtmlString.Empty;

  return MvcHtmlString.Create(resolvedLabelText);

}