【问题标题】:How to access viewmodel's property value in custom validation attribute to alter messages?如何在自定义验证属性中访问 viewmodel 的属性值以更改消息?
【发布时间】:2013-09-19 14:05:26
【问题描述】:

viewmodel 有许多字符串属性,例如Sample,如下所示。我的要求是根据我的视图模型中的布尔标志显示不同的验证消息。该标志是IsProposer 属性,如下所述:

[SampleAttribute(true, "bla prop", "foo add driver")]       
public string Sample { get; set; }

public bool IsProposer { get; set; }

我想创建一个验证属性,这样我就可以将它放在我所有的字符串属性上(需要验证)。然后根据该布尔标志的值,我将相应地传递消息。我的自定义验证属性如下:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
    public class SampleAttribute : RequiredAttribute
    {
        protected string ProposerErrorMessage { get; set; }
        protected string AdditionalDriverErrorMessage { get; set; }
        protected bool IsProposer { get; set; }
        public SampleAttribute(bool isProposer, string propmsg, string adddrivermsg)
        {
            ProposerErrorMessage = propmsg;
            IsProposer = isProposer;
            AdditionalDriverErrorMessage = adddrivermsg;

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (IsValid(value))
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(IsProposer ? ProposerErrorMessage : AdditionalDriverErrorMessage);
            }
        }
    }

现在的问题是,如您所见,我只是将 true 作为属性的第一个参数传递。在这里,我需要从 viewmodel 实例中传递 Isproposer 属性的值,以便我可以采取相应的行动。如何访问它?

【问题讨论】:

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


    【解决方案1】:

    我通过创建这样的属性解决了我的问题:

     /// <summary>
        /// This validation attribute is an extension to RequiredAttribute that can be used to choose either of the two 
        /// validation messages depending on a property in the context of same model.
        /// </summary>
        [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
        public class RequiredExtensionAttribute : RequiredAttribute
        {
            private string _errorMessageIfTruthy;
            private string _errorMessageIfFalsy; 
            private string _dependentProperty;
    
            public RequiredExtensionAttribute(string dependentproperty, string errorMessageIfTruthy, string errorMessageIfFalsy)
            {
                _errorMessageIfTruthy = errorMessageIfTruthy;
                _dependentProperty = dependentproperty;
                _errorMessageIfFalsy = errorMessageIfFalsy;
    
            }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                var propertyTestedInfo = validationContext.ObjectType.GetProperty(this._dependentProperty);
                if (propertyTestedInfo == null)
                {
                    return new ValidationResult(string.Format("unknown property {0}", this._dependentProperty));
                }
    
                var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
    
                if (IsValid(value))
                {
                    return ValidationResult.Success;
                }
                else
                {
                    return new ValidationResult((bool)propertyTestedValue ? _errorMessageIfTruthy : _errorMessageIfFalsy);
                }
            }
        }
    

    现在可以在以下模型中使用:

    [RequiredExtensionAttribute("IsProposerViewModel", "Please select your employment status.", "Please select this driver's employment status")]       
    public string EmploymentStatus { get; set; }
    public bool IsProposerViewModel { get; set; }
    

    -属性的第一个参数是IsProposerViewModel,即依赖值。

    【讨论】:

    • 解决了我的问题。我很高兴。
    • 如果IsProposerViewModel 属性位于EmploymentStatus 之前呢?当它们是循环属性时呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 2013-01-29
    • 2015-11-09
    • 2014-11-16
    • 2018-12-19
    • 1970-01-01
    相关资源
    最近更新 更多