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;
}
}
}
精彩评论