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

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

    If you want this to work with a metadata class you need to use the following code. I know its not pretty but it gets the job done and prevents you from having to write your maxlength properties in both the Entity class and the View:

    public static MvcHtmlString TextBoxFor2
    (
      this HtmlHelper htmlHelper,
      Expression> expression,
      object htmlAttributes = null
    )
    {
      var member = expression.Body as MemberExpression;
    
      MetadataTypeAttribute metadataTypeAttr = member.Member.ReflectedType
        .GetCustomAttributes(typeof(MetadataTypeAttribute), false)
        .FirstOrDefault() as MetadataTypeAttribute;
    
      IDictionary htmlAttr = null;
    
      if(metadataTypeAttr != null)
      {
        var stringLength = metadataTypeAttr.MetadataClassType
          .GetProperty(member.Member.Name)
          .GetCustomAttributes(typeof(StringLengthAttribute), false)
          .FirstOrDefault() as StringLengthAttribute;
    
        if (stringLength != null)
        {
          htmlAttr = new RouteValueDictionary(htmlAttributes);
          htmlAttr.Add("maxlength", stringLength.MaximumLength);
        }                                    
      }
    
      return htmlHelper.TextBoxFor(expression, htmlAttr);
    }
    

    Example class:

    [MetadataType(typeof(Person.Metadata))]
    public partial class Person
    {
      public sealed class Metadata
      {
    
        [DisplayName("First Name")]
        [StringLength(30, ErrorMessage = "Field [First Name] cannot exceed 30 characters")]
        [Required(ErrorMessage = "Field [First Name] is required")]
        public object FirstName { get; set; }
    
        /* ... */
      }
    }
    

提交回复
热议问题