我在我的 ASP.NET MVC 应用程序中使用xVal,这通常很棒。在Steve Sanderson 的博客文章之后,我创建了一个 DataAnnotationsValidationRunner 来对属性对象进行服务器端验证。这对于一个简单的类非常有用。例如人:
public static class DataAnnotationsValidationRunner
{
public static IEnumerable<ErrorInfo> GetErrors(object o)
{
return from prop in TypeDescriptor.GetProperties(o).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(o))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), o);
}
}
public class Person
{
[Required(ErrorMessage="Please enter your first name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your last name")]
public string LastName { get; set; }
}
但是,如果我向这个人添加一个 Address 属性,并用 DataAnnotation 属性标记 Address 类,它们将不会被验证。例如
public class Person
{
[Required(ErrorMessage="Please enter your first name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your last name")]
public string LastName { get; set; }
public Address Address { get; set; }
}
public class Address
{
[Required(ErrorMessage="Please enter a street address")]
public string Street { get; set; }
public string StreetLine2 { get; set; }
[Required(ErrorMessage = "Please enter your city")]
public string City { get; set; }
[Required(ErrorMessage = "Please enter your state")]
public string State { get; set; }
[Required(ErrorMessage = "Please enter your zip code")]
public string Zip { get; set; }
public string Country { get; set; }
}
一个问题是 DataAnnotationValidationRunner 不会遍历复杂的子属性。此外,如果将这些错误添加到错误集合中,则在添加到模型状态时仍需要正确添加前缀。例如。Person 错误是这样添加的:
catch (RulesException ex)
{
ex.AddModelStateErrors(ModelState, "person");
}
我认为地址规则例外需要以“person.address”为前缀。是否有支持使用 xVal 处理子对象验证的方法,或者创建扁平数据传输对象是唯一的解决方案?