控件的ASP.NET核心条件验证 [英] ASP.NET Core Conditional Validation for controls

查看:70
本文介绍了控件的ASP.NET核心条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在视图模型中具有这3个属性

For example, I have these 3 properties in my view model

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

这里的问题是我要设置属性

The problem here is that I want to make the properties

Critical 
Description

要求HasControl为true,否则为false,这是单选按钮控件.

required if HasControl is true or not required if it's false, which is a radio button control.

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

I have tried disabling the controls on client-side but they still fail when checking Modelstate.IsValid.

有没有办法处理这种情况?

Is there a way to handle this situation?

推荐答案

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

You need to implement IValidatableObject. Put validation checks in Validate method. return list of errors in the end.

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;
    }
}

这篇关于控件的ASP.NET核心条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆