c# - ASP.NET Core 控件条件验证

标签 c# asp.net-core model-validation

例如,我的 View 模型中有这 3 个属性

public class PageViewModel
{
            [Required]
            public bool? HasControl { get; set; }
            [Required] 
            public bool? Critical { get; set; }
            [Required]         
            public string Description { get; set; }
}

这里的问题是我想要创建属性

Critical 
Description

如果 HasControl 为 true,则为必需;如果为 false,则不需要,这是一个单选按钮控件。

我尝试禁用客户端的控件,但在检查 Modelstate.IsValid 时它们仍然失败。

有办法处理这种情况吗?

最佳答案

您需要实现IValidatableObject。将验证检查放入 Validate 方法中。最后返回错误列表。

public class PageViewModel : IValidatableObject
{
    public bool? HasControl { get; set; }
    public bool? Critical { get; set; }
    public string Description { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        List<ValidationResult> errors = new List<ValidationResult>();
        if (HasControl == true)
        {
            if (Critical == null)
                errors.Add(new ValidationResult($"{nameof(Critical)} is Required.", new List<string> { nameof(Critical) }));

            if (string.IsNullOrWhiteSpace(Description))
                errors.Add(new ValidationResult($"{nameof(Description)} is Required.", new List<string> { nameof(Description) }));
        }
        return errors;
    }
}

关于c# - ASP.NET Core 控件条件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58744905/

相关文章:

c# - 人们在使用 TVP 将 DataTable/Collection 发送到 SQL Server 时遇到了什么问题

c# - 循环遍历 c# 字典中的项目

c# - 使用 LibTiff.Net 2.3 库时,多 strip TIFF 和单条 TIFF 有什么区别

asp.net-core - .NET Core 3.1 User.Identity.Name 使用 Windows 身份验证时始终为空

c# - 复杂模型/子模型验证 (MVC) 的最佳方法

c# - 如何对 MVC3 列表中的对象设置的拾取属性进行模型验证?

c# - 如何使用 C# 从今天的日期和当前时间获取准确的 3 个月前的日期和时间

asp.net-core - 我的自定义 ASP.Net 5 MVC 6 标签助手应该有一个 asp- 前缀吗?

c# - 通过https的docker中的Asp.Net-Core应用程序

ruby-on-rails - Rails 和模型验证