【问题标题】:How to pass view model data through to ValidationAttribute?如何将视图模型数据传递给 ValidationAttribute?
【发布时间】:2014-08-04 11:22:17
【问题描述】:

所以我有一个简单的自定义验证属性:

public class MyCustomValidator : CustomValidationAttribute
{
    public bool IsLive { get; set; }

    public MyCustomValidator()
    {
        //Service locator stuff
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return ValidationResult.Success;
    }
}

MyCustomValidor 继承了下面的类,因为我的所有自定义验证器都需要访问它。

public abstract class CustomValidationAttribute : ValidationAttribute
{
    public Type MessageResource { get; set; }

    public string MessagePrefix { get; set; }
}

然后我在我的 viewModel 中调用它,看起来有点像这样:

public class MyViewModel
{
    private static bool IsWebLive;

    [MyCustomValidator(IsWebLive = IsWebLive, MessageResource = typeof(MyResourceFile), MessagePrefix = "ErrorMessage")]
    public string SampleValue { get; set; }
}

在我将私有 IsWebLive 传递到 validator 的地方,我收到一条错误消息 an attribute argument must be a constant expression, typeof expression or array. 我知道我可能做错了。但是我怎么能把这个布尔值传递给验证器,因为我无法访问系统中其他任何地方的设置;

我也不能在MyCustomValidator 中私下设置IsLive/MessageResource/MessagePrefix,因为我的自定义验证器内容是通用的,并且MessagePrefixMessageResource 在我的所有自定义验证器中都可以访问。

【问题讨论】:

    标签: c# asp.net-mvc validation viewmodel validationattribute


    【解决方案1】:

    抱歉,这是不可能的。属性的构造函数参数必须在编译时知道,因为它们旨在作为类型或方法的元数据NOT是每个调用或实例都会使用的东西。

    【讨论】:

    • 好的,谢谢,我认为可能是这样的,但我还是想问一下。
    【解决方案2】:

    您可以做的是简单地使用 CustomValidationAttribute 为其提供一个静态方法来进行验证。调用静态方法时,您提供的参数之一是验证上下文,它将包含视图模型中 ObjectInstance 属性下的所有属性。因此,例如,您可以简单地让 IsWebLive 可供您在静态方法中进行条件测试。不需要继承也不需要 IsLive 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 2011-08-10
      • 1970-01-01
      • 2014-09-14
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多