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

前端 未结 7 664
攒了一身酷
攒了一身酷 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:13

    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);
    }
    
    0 讨论(0)
提交回复
热议问题