gpt4 book ai didi

c# - .NET:一般的 DataAnnotation 属性

转载 作者:行者123 更新时间:2023-11-30 14:20:09 26 4
gpt4 key购买 nike

ASP.NET MVC 2 将支持基于 DataAnnotation 属性的验证,如下所示:

public class User
{
[Required]
[StringLength(200)]
public string Name { get; set; }
}

如何使用纯 .NET(不使用 MVC 绑定(bind)、 Controller 方法等)检查当前模型状态是否有效?

理想情况下,它应该是一个方法:

bool IsValid(object model);

最佳答案

此代码示例来自 Steve Sanderson 的 blog关于xVal (它使用 DataAnnotationsAttribute 来验证属性)。基本上,您只需要使用反射枚举属性并检查 IsValid() :.

internal static class DataAnnotationsValidationRunner
{
public static IEnumerable<ErrorInfo> GetErrors(object instance)
{
return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(instance))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
}
}

关于c# - .NET:一般的 DataAnnotation 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1650209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com