如何在HtmlHelper扩展期间评估模型上的数据注释?

时间:2012-03-21 14:11:14

标签: asp.net-mvc-3

我有一个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。如何获得酒店的属性?

1 个答案:

答案 0 :(得分: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 });
}