2011-07-06 39 views
2

我如何才能将DisplayName属性的属性值替代在我看来使用Html.LabelFor()Html.LabelFor()对我来说并不冷静,因为它让我感到<label for=""></label>这破坏了我的页面布局。 因此,这里是样品型号的财产:提前只是文本的显示名称

[DisplayName("House number")] 
     [Required(ErrorMessage = "You must specify house number")] 
     [Range(1, 9999, ErrorMessage = "You have specify a wrong house number")] 
     public UInt32? buildingNumber 
     { 
      get { return _d.buildingNumber; } 
      set { _d.buildingNumber = value; } 
     } 

谢谢,伙计们!

回答

2

你可以从元数据获取它:

<% 
    var displayName = ModelMetadata 
     .FromLambdaExpression(x => x.buildingNumber, Html.ViewData) 
     .DisplayName; 
%> 

<%= displayName %> 
+0

感谢达林!这就是我需要的。 – kseen

3

这应该从元数据显示名称:

@ModelMetadata.FromLambdaExpression(m => m.buildingNumber, ViewData).DisplayName 

编辑:

我觉得你还是可以使用的语句MVC2,只需更改@:

<%:ModelMetadata.FromLamb daExpression(m => m.buildingNumber,ViewData).DisplayName%>

+0

感谢您的回答马丁!你的答案是MVC3剃刀视图引擎,但我使用MVC2,所以我不能。 – kseen

3

借用http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx,我创建了一个扩展方法来执行此操作。它带有始终安全的跨度标签输出。你也可以修改这个来完全省略span标签(消除两个重载,因为在这种情况下你永远不能获取属性)。

与此内容创建一个类时,请确保您的网页导入该类的命名空间,然后在视图中使用这个喜欢Html.DisplayNameFor(x => x.Name)

public static class DisplayNameForHelper 
{ 
    public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) 
    { 
     return DisplayNameFor(html, expression, new RouteValueDictionary()); 
    } 

    public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes) 
    { 
     return DisplayNameFor(html, expression, new RouteValueDictionary(htmlAttributes)); 
    } 

    public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes) 
    { 

     ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); 
     string htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
     string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); 
     if (String.IsNullOrEmpty(labelText)) 
     { 
      return MvcHtmlString.Empty; 
     } 
     TagBuilder tag = new TagBuilder("span"); 
     tag.MergeAttributes(htmlAttributes); 
     tag.SetInnerText(labelText); 
     return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal)); 

    } 
} 
+0

我只在MVC3中测试过这个,因为我目前没有一个MVC2项目,但我希望它在没有太多麻烦的情况下也能正常工作。 –