如何从DataAnnotations获取StringLength

问题描述 投票:6回答:5

更新建议后,我仍然收到错误

尝试用.SingleOrDefault()FirstOrDefault()

我需要检索StringLength注释值,这是我的代码,但我收到以下错误。

我试图从here实现几乎相同的代码,但得到错误:

序列不包含任何元素

    public static class DataAnnotation
    {
        public static int GetMaxLengthFromStringLengthAttribute(Type modelClass, string propertyName)
        {
            int maxLength = 0;
            var attribute = modelClass.GetProperties()
                            .Where(p => p.Name == propertyName)
                            .Single()
                            .GetCustomAttributes(typeof(StringLengthAttribute), true)
                            .Single() as StringLengthAttribute;

            if (attribute != null)
                maxLength = attribute.MaximumLength;

            return 0;
        }
    }

//调用:

int length = DataAnnotation.GetMaxLengthFromStringLengthAttribute(typeof(EmployeeViewModel), "Name");


public class EmployeeViewModel
{         
    [StringLength(20, ErrorMessage = "Name cannot be longer than 20 characters.")] 
    public string Name{ get; set; }
}
c# asp.net-mvc data-annotations
5个回答
© www.soinside.com 2019 - 2024. All rights reserved.