2011-03-18 112 views
0

我有一個強烈類型的視圖,其型號爲LogOnModel。這LogOnModel已anotated性質類似這樣的:如何從強類型自定義HtmlHelper訪問模型中屬性的屬性?

[Required(ErrorMessage = "Please enter your password")] 
[DataType(DataType.Password)] 
[Display(Name = "Password", Description = "Your secreet password")] 
public string Password { get; set; } 

他們都有Display anotation與Display.Descripion屬性集。 我想創建HtmlHelper擴展方法,該方法將輸出包含Display.Description屬性值的<span>

因此,舉例來說,如果我打電話給我的擴展方法DescriptionFor比這個代碼:

<%: Html.DescriptionFor(m => m.Password) %> 

應該產生下面的HTML:<span>Your secreet password</span>

感謝所有的想法和代碼。

+0

我會非常高興,如果你留下了評論,如果事情是不是清楚我的問題。謝謝。 – drasto 2011-03-18 05:22:04

回答

1

看到這個問題:Extract Display name and description Attribute from within a HTML helper

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

MSDN:ModelMetadata Class