2011-02-11 58 views
7

我建立一個自定義的HTML.LabelFor幫手,看起來像這樣:提取物顯示名稱和說明屬性從HTML幫助中

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression, Boolean showToolTip) 
{ 
    var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData); 
    ... 
} 

爲了能夠獲得該屬性的專有名稱,我用下面的代碼:

metadata.DisplayName 

而且在模型視圖類我得到的財產:

[DisplayName("Titel")] 

問題是我還需要說明。有一個稱爲顯示的屬性,它具有名稱和描述,但我沒有看到如何在上面的代碼中使用元數據變量來提取它?

回答

19

免責聲明:以下的作品只能用ASP.NET MVC 3(見底部的更新,如果您使用的是以前的版本)

假設下面的模式:

public class MyViewModel 
{ 
    [Display(Description = "some description", Name = "some name")] 
    public string SomeProperty { get; set; } 
} 

而下面的視圖:

<%= Html.LabelFor(x => x.SomeProperty, true) %> 

內自定義助手,你可以獲取從元數據信息:

public static MvcHtmlString LabelFor<TModel, TValue>(
    this HtmlHelper<TModel> self, 
    Expression<Func<TModel, TValue>> expression, 
    bool showToolTip 
) 
{ 
    var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData); 
    var description = metadata.Description; // will equal "some description" 
    var name = metadata.DisplayName; // will equal "some name" 
    // TODO: do something with the name and the description 
    ... 
} 

備註:有在同一個模型財產[DisplayName("foo")][Display(Name = "bar")]是多餘的,在[Display]屬性所使用的名稱具有優先權的metadata.DisplayName


UPDATE:

我以前的答案將不會與ASP.NET MVC 2.0。有幾個屬性,在.NET 3.5中不可能默認填充DataAnnotations,而Description就是其中之一。在ASP.NET實現這一MVC 2.0,你可以使用自定義的模型元數據提供商:

public class DisplayMetaDataProvider : DataAnnotationsModelMetadataProvider 
{ 
    protected override ModelMetadata CreateMetadata(
     IEnumerable<Attribute> attributes, 
     Type containerType, 
     Func<object> modelAccessor, 
     Type modelType, 
     string propertyName 
    ) 
    { 
     var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); 

     var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault(); 
     if (displayAttribute != null) 
     { 
      metadata.Description = displayAttribute.Description; 
      metadata.DisplayName = displayAttribute.Name; 
     } 
     return metadata; 
    } 
} 

,你會在Application_Start登記:

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    RegisterRoutes(RouteTable.Routes); 
    ModelMetadataProviders.Current = new DisplayMetaDataProvider(); 
} 

,然後助手應該按預期工作:

public static MvcHtmlString LabelFor<TModel, TValue>(
    this HtmlHelper<TModel> self, 
    Expression<Func<TModel, TValue>> expression, 
    bool showToolTip 
) 
{ 
    var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData); 
    var description = metadata.Description; // will equal "some description" 
    var name = metadata.DisplayName; // will equal "some name" 
    // TODO: do something with the name and the description 
    ... 
} 
+0

謝謝!但是這不起作用,DisplayName和Description是空的?請注意,這是在MVC2而不是MVC3。如果我解決了這個問題,你的解決方案只能在MVC3中使用? – Banshee 2011-02-11 21:04:53