如何从DataAnnotations获取StringLength

Nic*_*ahn 7 c# asp.net-mvc data-annotations

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

.SingleOrDefault()或试过FirstOrDefault()

在此输入图像描述

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

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

序列不包含任何元素

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

//调用:

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; }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*ahn 7

我能够想出来,经过测试并且工作得很好,万一其他人在寻找!

  StringLengthAttribute strLenAttr = typeof(EmployeeViewModel).GetProperty(name).GetCustomAttributes(typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().SingleOrDefault();
  if (strLenAttr != null)
  {
     int maxLen = strLenAttr.MaximumLength;
  }
Run Code Online (Sandbox Code Playgroud)