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 found Darin's reflection based approach to be especially helpful. I found that it was a little more reliable to use the metadata ContainerType
as the basis to get the property info, as this method can get called within mvc editor/display templates (where TModel
ends up being a simple type such as string
).
public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes
)
{
var metadata = ModelMetadata.FromLambdaExpression( expression, new ViewDataDictionary<TModel>( htmlHelper.ViewDataContainer.ViewData ) );
var stringLength = metadata.ContainerType.GetProperty(metadata.PropertyName)
.GetCustomAttributes(typeof(StringLengthAttribute), false)
.FirstOrDefault() as StringLengthAttribute;
var attributes = (IDictionary<string, object>)new RouteValueDictionary(htmlAttributes);
if (stringLength != null)
{
attributes.Add("maxlength", stringLength.MaximumLength);
}
return htmlHelper.TextBoxFor(expression, attributes);
}