【发布时间】:2013-08-16 12:23:34
【问题描述】:
我有两种不同的类型:
public class Person
{
public string Name { get; set; }
public bool IsActive { get; set; }
public Contact ContactDetails { get; set; }
}
public class Contact
{
[RequiredIfActive]
public string Email { get; set; }
}
我需要的是根据父模型字段的某些状态对内部模型字段执行条件声明性验证 - 在此特定示例中,如果启用了 IsActive 选项,则必须填写 Email。
我不想重新组织这些模型分类,同时我需要使用基于属性的方法。似乎从属性中无法访问父模型的验证上下文。如何到达或注入那里?
public class RequiredIfActiveAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
/* validationContext.ObjectInstance gives access to the current
Contact type, but is there any way of accessing Person type? */
编辑:
我知道如何使用 Fluent Validation 实现条件验证,但我不是在问这个问题(我不需要 Fluent Validation 方面的支持)。但是我想知道,是否存在从System.ComponentModel.DataAnnotations.ValidationAttribute 内部访问父模型的任何方法。
【问题讨论】:
-
Fluent 验证比默认的 MVC 验证要好得多。在使用默认 mvc 验证 4 年后,我在 3 个月前切换到 fluent 验证。
-
@Softlion:这个问题主要是我的好奇心,我不想验证任何东西。在这种特殊情况下,我也不想简化我的生活。这就是为什么 Fluent Validation 建议在任何层面都不会针对我的问题。
标签: .net asp.net-mvc data-annotations asp.net-mvc-validation system.componentmodel