Asp.net mvc 2 ASP.NET MVC 2:自定义验证,访问整个模型?

Asp.net mvc 2 ASP.NET MVC 2:自定义验证,访问整个模型?,asp.net-mvc-2,customvalidator,Asp.net Mvc 2,Customvalidator,我已经被引导到一篇非常好的文章,它展示了如何从头到尾创建自定义验证器。我唯一的问题是,这只适用于单个字段: 如果需要针对模型中的2个或更多属性进行验证,该怎么办?如何将整个模型传递到验证器 注意:要清楚,我真的不想在回邮时求助于验证整个模型。。。这将无法达到此方法的目的。您需要使用自定义的“验证”属性,而不是单个属性来装饰模型: [AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = true, Inherited =

我已经被引导到一篇非常好的文章,它展示了如何从头到尾创建自定义验证器。我唯一的问题是,这只适用于单个字段:

如果需要针对模型中的2个或更多属性进行验证,该怎么办?如何将整个模型传递到验证器


注意:要清楚,我真的不想在回邮时求助于验证整个模型。。。这将无法达到此方法的目的。

您需要使用自定义的“验证”属性,而不是单个属性来装饰模型:

[AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class MyCustomValidatorAttribute : ValidationAttribute 
{
    public override bool IsValid(object value) 
    {
        // value here will be the model instance you could cast
        // and validate properties
        return true;
    }
}
然后用它装饰您的模型:

[MyCustomValidator]
public class MyViewModel
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

作为执行验证的数据注释的替代方案,我强烈推荐您。它还具有。

您需要使用自定义的“验证”属性,并用它来装饰模型,而不是单个属性:

[AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class MyCustomValidatorAttribute : ValidationAttribute 
{
    public override bool IsValid(object value) 
    {
        // value here will be the model instance you could cast
        // and validate properties
        return true;
    }
}
然后用它装饰您的模型:

[MyCustomValidator]
public class MyViewModel
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}
作为执行验证的数据注释的替代方案,我强烈推荐您。它还有。

[AttributeUsageAttributeTargets.Class]?[AttributeUsageAttributeTargets.Class]?