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

前端 未结 7 698
攒了一身酷
攒了一身酷 2020-11-30 18:33

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

7条回答
  •  死守一世寂寞
    2020-11-30 19:04

    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" })%>
    

提交回复
热议问题