2012-03-21 38 views
0

我有一個的HtmlHelper擴展方法,看起來像這樣:如何在HtmlHelper擴展期間評估模型上的數據註釋?

public static MvcHtmlString TextBoxWithMaxLengthFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string name) 
{ 
    return html.TextBoxFor(expression, new { maxlength = 50 }); 
} 

我想與在給定的屬性的數據StringLength註釋的值,以取代50,如果一個被定義。我該如何去了解房產的屬性?

回答

2

找到了答案:

public static MvcHtmlString TextBoxWithMaxLengthFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression) 
{ 
    var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); 
    var property = html.ViewData.Model.GetType().GetProperty(metadata.PropertyName); 
    var attributes = property.GetCustomAttributes(typeof(StringLengthAttribute), true); 
    var maxLength = attributes.Length > 0 ? ((StringLengthAttribute)attributes[0]).MaximumLength : 50; 
    return html.TextBoxFor(expression, new { maxlength = maxLength }); 
}