2011-07-06 36 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項目,但我希望它在沒有太多麻煩的情況下也能正常工作。 –