c# – .NET:一般的DataAnnotation属性
发布时间:2020-12-16 01:32:57 所属栏目:百科 来源:网络整理
导读:ASP.NET MVC 2将支持基于DataAnnotation属性的验证,如下所示: public class User{ [Required] [StringLength(200)] public string Name { get; set; }} 如何仅使用纯.NET(不使用MVC绑定,控制器方法等)检查当前模型状态是否有效? 理想情况下,这将是一个单一
ASP.NET MVC 2将支持基于DataAnnotation属性的验证,如下所示:
public class User { [Required] [StringLength(200)] public string Name { get; set; } } 如何仅使用纯.NET(不使用MVC绑定,控制器方法等)检查当前模型状态是否有效? 理想情况下,这将是一个单一的方法: 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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |