2012-06-05 31 views
1

我們有一個具有以下簽名的自定義HTML助手。檢索[顯示] HTML助手中的屬性名稱

public static MvcHtmlString TextBoxFor<TModel, 
    TProperty>(this HtmlHelper<TModel> helper, 
    Expression<Func<TModel, TProperty>> property) 
{ 
    var htmlAttributes = new Dictionary<string, object>(); 

    // .... 

    return helper.TextBoxFor(property, htmlAttributes); 
} 

我想在這裏實現placeholder屬性,它應該被設置爲標籤此控件。該標籤可以是字符串常量,也可以是爲屬性[Display]屬性指定的字符串。

有沒有什麼辦法讓我從這個幫助函數中獲得這個標籤?

回答

0

這似乎工作:

ModelMetadata metadata = ModelMetadata.FromLambdaExpression(property, helper.ViewData); 
string htmlFieldName = ExpressionHelper.GetExpressionText(property); 
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); 
if (!String.IsNullOrWhiteSpace(labelText)) 
    // labelText contains the label