这个问题与 Asp.net MVC5 有关。 类似问题在这里回答: https://stackoverflow.com/questions/7674841/net-mvc3-conditionally-validating-property-which-relies-on-parent-object-proper
我有以下 View 模型:
public class ParentModel
{
public DateTime EffectiveDate { get; set; }
public List<ChildModel> Children { get; set; }
//.....
//.....
}
public class ChildModel
{
[DateOfBirthRange(ErrorMessage = "Date of Birth must be within range")]
public DateTime DateOfBirth { get; set; }
//.....
//.....
}
public class DateOfBirthRange : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return null;
//here validationContext.ObjectInstance is ChildModel
//How do i get the Effective Date of ParentModel?
}
}
ChildModel 是一个列表,我需要验证所有子模型的 DateOfBith w.r.t ParentModel 中的有效日期值。
最佳答案
基于 .NET DataAnnotations 的验证不提供递归验证。但是,您可以按照说明扩展它 here .这样做,您可以控制 ValidationContext
(用于验证子对象)的创建方式。
因此,在上述文章的 ValidateObjectAttribute
中,在 IsValid
中实例化新的 ValidationContext
时,而不是传递 null
作为服务提供者,您可以传递自定义 IServiceProvider
,它为您提供父验证上下文,并使用其 ObjectInstance
获取正在验证的父对象。
关于c# - 在 Validation Context 中获取子属性中的父对象属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21312345/