【问题标题】:Access Controller context in custom ValidationAttribute自定义 ValidationAttribute 中的访问控制器上下文
【发布时间】:2014-08-09 23:24:51
【问题描述】:

我正在使用 ValidationAttribute 实现自定义验证器:

public class CustomAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid (object value, ValidationContext validationContext)
    {
        //...
    }
}

但要运行验证,我需要访问作为应用程序基本控制器一部分的变量(它与当前登录的用户相关)。我怎样才能得到它?

【问题讨论】:

    标签: asp.net-mvc validation asp.net-mvc-4


    【解决方案1】:

    如果您可以使用变量填充模型属性,您可以这样做:

    型号:

    [CustomAttribute("MyVariableAsModelProperty", "Failed Validation!")
    public string ValidateThis{get; set;}
    public string MyVariableAsModelProperty{get; set;}
    

    您的自定义验证器:

    public class CustomAttribute : ValidationAttribute
    {
        string otherPropertyName;
        public CustomAttribute(string otherPropertyName, string errorMessage)
                    : base(errorMessage)
               {
                    this.otherPropertyName = otherPropertyName;
                }
                protected override ValidationResult IsValid (object value, ValidationContext validationContext)
                {
                    var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
                    var referenceProperty = (string)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
                    //...
                }
    

    现在您有 2 个值要比较:value 是要验证的模型属性,referenceProperty 是变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2012-06-17
      相关资源
      最近更新 更多