I am working on an MVC2 application and want to set the maxlength attributes of the text inputs.
I have already defined the stringlength attribute on the Model objec
I am not aware of any way to achieve this without resorting to reflection. You could write a helper method:
public static MvcHtmlString CustomTextBoxFor(
this HtmlHelper htmlHelper,
Expression> expression,
object htmlAttributes
)
{
var member = expression.Body as MemberExpression;
var stringLength = member.Member
.GetCustomAttributes(typeof(StringLengthAttribute), false)
.FirstOrDefault() as StringLengthAttribute;
var attributes = (IDictionary)new RouteValueDictionary(htmlAttributes);
if (stringLength != null)
{
attributes.Add("maxlength", stringLength.MaximumLength);
}
return htmlHelper.TextBoxFor(expression, attributes);
}
which you could use like this:
<%= Html.CustomTextBoxFor(model => model.Address1, new { @class = "text long" })%>