2011-07-06 6 views
2

私はビュー内でHtml.LabelFor()を使用する代わりに、DisplayNameというモデルのプロパティの属性の値を入れてもいいですか? Html.LabelFor()は私のために私が私のページのレイアウトを壊す<label for=""></label>を得る原因のためにまともでない。だからここ は、モデルのプロパティのサンプルです:事前にDisplayNameのテキストだけ

[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

これは、メタデータからのDisplayNameを取得する必要があります:

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

編集:

私はあなたがまだのためのステートメントを使用することができると思いますMVC2、ちょうど@を変更する:

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

+0

あなたの答えをありがとうMartin!あなたの答えはMVC3 Razorビューエンジンですが、私はMVC2を使用していますので、それはできません。 – kseen

3

http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspxから大きく借りて、これを行う拡張メソッドを作成しました。常に安全なスパンタグで出力します。また、これを変更してスパンタグを完全に省略することもできます(この場合、属性を決して使用できないため、2つのオーバーロードを排除します)。

は、あなたのページは、その後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プロジェクトは現時点では手軽でしたが、そこに問題がなくてもうまくいくと思います。 –

関連する問題