开发者

How to find the value of an attribute

How can I find the value of an attribute? I need to check the value and set the textbox maxlength to that value. Here is an example of the value I'm looking to retrieve.

public class DogClass
    {
        [StringLength(5)]
        public string LegalNam开发者_StackOverflowe
        {
        }


You can use reflection to get this info. Below is a snippet that should get you started.

protected void GetStringLength(object objDog) {
    // loop through each property in object
    foreach (PropertyInfo pi in objDog.GetType().GetProperties())
    {
        // for each object property, get the SringLength tag (if there is one)
        foreach (Attribute attribute in Attribute.GetCustomAttributes(pi, typeof(StringLengthAttribute), true))
           {
                // we'll assume there is only one 
                var stringLenVal = (attribute as StringLengthAttribute).MaximumLength;
                break;
           }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜