自定义验证属性不称为 ASP.NET MVC

问题描述 投票:0回答:1

大家好,我创建了自定义验证属性并将其分配给类级别验证。不幸的是,它没有被调用。我尝试了一切认为可以解决问题的方法。然而,我花了几个小时,却找不到验证机制未调用该属性。

为了说明你,我放置了以下代码。

属性:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class BooleanDependencyAttribute : ValidationAttribute {
    private const string _defaultErrorMessage = "กรุณากรอก{0}";
    private readonly object _typeId = new object();

    public string DependencyPropertyName { get; private set; }
    public string DependentPropertyName { get; private set; }

    public BooleanDependencyAttribute(string dependencyPropertyName,
                                      string dependentPropertyName)
        : base(_defaultErrorMessage) {
        DependencyPropertyName = dependencyPropertyName;
        DependentPropertyName = dependentPropertyName;
    }

    public override object TypeId {
        get { return _typeId; }
    }

    public override string FormatErrorMessage(string name) {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                             name);
    }

    public override bool IsValid(object value) {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(value);
        bool dependencyValue =
            (bool)properties.Find(DependencyPropertyName, true /* ignoreCase */)
                .GetValue(value);
        object dependentValue =
            properties.Find(DependentPropertyName, true /* ignoreCase */)
                .GetValue(value);
        if (dependencyValue) {
            return true;
        } else {
            if (dependentValue == null) {
                return false;
            } else {
                return true;
            }
        }
    }
}

视图模型:

[BooleanDependency("ReleaseNow", "ReleaseDate",
                   ErrorMessage = "Please enter release date")]
public class ContentCreate {
    public string Title { get; set; }

    public DateTime? ReleaseDate { get; set; }

    public string Details { get; set; }

    public string Abstract { get; set; }

    public string Tags { get; set; }

    public bool ReleaseNow { get; set; }
}

请你帮我解决这个问题。

c# asp.net-mvc asp.net-mvc-2
1个回答
7
投票

我找到了解决方案。事实上,类级别的验证是在所有属性级别的验证有效之后调用的。因此我需要完成其他必需的属性,然后 BooleanDependencyAttribute 将被调用并获得有效值。

感谢查看,编辑标题和标签。

© www.soinside.com 2019 - 2024. All rights reserved.