的StringLength更新建議後,我仍然得到錯誤如何從DataAnnotations
都嘗試用.SingleOrDefault()
或FirstOrDefault()
我需要檢索StringLength
標註值,在這裏是我的代碼,但我發現了以下錯誤。
我試圖實現幾乎從here相同的代碼,但得到的錯誤:
Sequence contains no elements
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; }
}
如果你有'MinimumLength = 1',那麼你正在執行有最小長度?即使這些字段是可選的? –
@AbuHamzah: - 更新我的答案。請檢查! –
我更新了我的問題,仍然得到同樣的錯誤 –