2010-04-07 20 views
8

Mam następującyAsp.net MVC Label Dla

<label for="Forename">Forename</label> 
<%= Html.TextBoxFor(m => m.Customer.Name.Forename) %> 

Problem z tym jest to, że jest wyświetlany jako

<label for="Forename">Forename</label> 
<input type="text" value="" name="Customer.Name.Forename" id="Customer_Name_Forename"> 

nie co chcę ofc.

Chciałbym rozszerzenie, aby poprawnie renderować etykietę (tj. Z atrybutem for = "" mającym wartość identyfikatora wejściowego), czy jest coś w MVC 2, które robi to nativly zanim zacznę pisać własne rozszerzenie?

Odpowiedz

13
<%= Html.LabelFor(m => m.Customer.Name.Forename) %> 
<%= Html.TextBoxFor(m => m.Customer.Name.Forename) %> 
11

Poniższa wola pozwala nadrzędnymi domyślną nazwę wyświetlaną, alternatywą do korzystania z niżej jest vandalize model używając atrybutu

Wykorzystanie

<%= Html.LabelFor(m => m.Customer.Name.Forename, "First Name")%> 

Kod

[DisplayName]
namespace System.Web.Mvc.Html 
{ 
    public static class LabelExtensions 
    { 
     public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string displayName) 
     { 
      return LabelHelper(html, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), displayName); 
     } 

     internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string displayName) 
     { 
      string str = displayName ?? metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>()); 
      if (string.IsNullOrEmpty(str)) 
      { 
       return MvcHtmlString.Empty; 
      } 
      TagBuilder builder = new TagBuilder("label"); 
      builder.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); 
      builder.SetInnerText(str); 
      return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal)); 
     } 
    } 
} 
+0

Doceń kod s nippet =) – afreeland

+0

"niszczyć swój model za pomocą atrybutu [DisplayName]" - lol – Alex

+0

@Alex O tak, to był okropny pomysł, dobra robota, wiem, że lepiej 4 i pół roku później. –

Powiązane problemy