maxlength attribute of a text box from the DataAnnotations StringLength in Asp.Net MVC

asp.net-mvc, validation

Solution

I am not aware of any way to achieve this without resorting to reflection. You could write a helper method:

public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression, 
    object htmlAttributes
)
{
    var member = expression.Body as MemberExpression;
    var stringLength = member.Member
        .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);
}

which you could use like this:

<%= Html.CustomTextBoxFor(model => model.Address1, new { @class = "text long" })%>

Problem

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 object using data annotations and it is validating the length of entered strings correctly. I do not want to repeat the same setting in my views by setting the max length attribute manually when the model already has the information. Is there any way to do this? Code snippets below: From the Model: ``` [Required, StringLength(50)] public string Address1 { get; set; } ``` From the View: ``` <%= Html.LabelFor(model => model.Address1) %> <%= Html.TextBoxFor(model => model.Address1, new { @class = "text long" })%> <%= Html.ValidationMessageFor(model => model.Address1) %> ``` What I want to avoid doing is: ``` <%= Html.TextBoxFor(model => model.Address1, new { @class = "text long", maxlength="50" })%> ``` I want to get this output: ``` <input type="text" name="Address1" maxlength="50" class="text long"/> ``` Is there any way to do this?

Original source

Related problems