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