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

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

    Here are some static methods you can use to get the StringLength, or any other attribute.

    using System;
    using System.Linq;
    using System.Reflection;
    using System.ComponentModel.DataAnnotations;
    using System.Linq.Expressions;
    
    public static class AttributeHelpers {
    
    public static Int32 GetStringLength(Expression> propertyExpression) {
        return GetPropertyAttributeValue(propertyExpression,attr => attr.Length);
    }
    
    //Optional Extension method
    public static Int32 GetStringLength(this T instance,Expression> propertyExpression) {
        return GetStringLength(propertyExpression);
    }
    
    
    //Required generic method to get any property attribute from any class
    public static TValue GetPropertyAttributeValue(Expression> propertyExpression,Func valueSelector) where TAttribute : Attribute {
        var expression = (MemberExpression)propertyExpression.Body;
        var propertyInfo = (PropertyInfo)expression.Member;
        var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;
    
        if (attr==null) {
            throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);
        }
    
        return valueSelector(attr);
    }
    
    }
    

    Using the static method...

    var length = AttributeHelpers.GetStringLength(x => x.Address1);
    

    Or using the optional extension method on an instance...

    var player = new User();
    var length = player.GetStringLength(x => x.Address1);
    

    Or using the full static method for any other attribute...

    var length = AttributeHelpers.GetPropertyAttributeValue(prop => prop.Address1,attr => attr.MaximumLength);
    

    Inspired by the answer here... https://stackoverflow.com/a/32501356/324479

提交回复
热议问题