【问题标题】:How to use mvc dataannotations to validate property value if other property is set to true?如果其他属性设置为 true,如何使用 mvc 数据注释来验证属性值?
【发布时间】:2016-09-22 08:05:00
【问题描述】:

我正在尝试验证表单提交但我只想在另一个属性设置为 true 时验证一个属性。

我的两个属性:

[DisplayName(Translations.Education.IsFeaturette)]
public  bool IsFeaturette { get; set; }

[DisplayName(Translations.Education.AddFeaturetteFor)]
[CusomValidatorForFeaturettes(IsFeaturette)]
public string[] Featurettes { get; set; }

自定义注解:

public class CusomValidatorForFeaturettes: ValidationAttribute
{
    private readonly bool _IsFeatturette;
    public CusomValidatorForFeaturettes(bool isFeatturette): base("NOT OK")
    {
        _IsFeatturette = isFeatturette;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null && _IsFeatturette )
        {
            var errorMessage = FormatErrorMessage(validationContext.DisplayName);
            return new ValidationResult(errorMessage);

        }
        return ValidationResult.Success;
    }
}

如果 isfeature 为真,那么 Featurettes 必须有一个值!

我得到错误:

非静态字段、方法或 属性“EducationViewModel.IsFeaturette”

我不能将这个属性设为静态因为这会给我带来问题,因为这个属性是用 enityframework 设置的,我不希望更改任何内容。如何在不使属性静态的情况下完成此操作?

【问题讨论】:

  • 考虑使用foolproof 条件属性,包括它们的[RequiredIfTrue] 属性,这将为您提供客户端和服务器端验证
  • 感谢您的提示,但是我现在想避免使用框架。你知道怎么解决是这样的吗?
  • 您不能将属性作为参数传递给属性-它必须是string(一个常量值)-在您的情况下[CusomValidatorForFeaturettes("IsFeaturette")]表示“其他”属性的名称.

标签: c# asp.net-mvc-5 data-annotations


【解决方案1】:

属性在编译时添加到程序集的元数据中,因此其参数必须在编译时已知。生成错误是因为您将属性 (bool IsFeaturette) 的值传递给非静态属性(在运行时可能是 truefalse)。

而是传递一个字符串来表示要比较的属性的名称,并在方法中使用反射来获取属性的值。

public  bool IsFeaturette { get; set; }

[CusomValidatorForFeaturettes("IsFeaturette")]
public string[] Featurettes { get; set; }

并将验证属性修改为

public class CusomValidatorForFeaturettes: ValidationAttribute
{
    private readonly string _OtherProperty;

    public CusomValidatorForFeaturettes(string otherProperty): base("NOT OK")
    {
        _OtherProperty = otherProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Get the dependent property 
        var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_OtherProperty);
        // Get the value of the dependent property 
        var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
        ......

然后您可以将otherPropertyValue 转换为bool 并进行条件检查。

我还建议您阅读The Complete Guide to Validation in ASP.NET-MVC-3 Part-2 以更好地了解如何实现验证属性,包括如何实现IClientValidatable 以便您同时获得服务器端和客户端验证。我还建议您将方法重命名为(例如)RequiredIfTrueAttribute 以更好地反映它的作用。

另请注意,foolproof 有很多用于 MVC 的验证属性。

最后一点,您当前的实现特定于对一个属性(IsFeaturette 的值)的依赖,这对于验证属性毫无意义——您最好只检查控制器中的值并添加ModelStateError。上面的代码意味着您可以传入任何属性名称(只要该属性是 typeof bool),这是验证属性应该允许的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    相关资源
    最近更新 更多