1

In my Asp.net MVC app, I have a custom validator class V and an (ADO.NET Entities) entity model E.

class V : ValidationAttribute
{    
    public override bool IsValid(object value)
    {
        ...        
        if (hasErrors)
            ErrorMessage = errorMsg;
        ...        
    }    
}
public partial class E //the entity model
{    
    [V]
    public object A {get;set;}    
}

I applied validator V to a custom property P in entity model E. Validator V sets the error message in IsValid.

However, it seems as though an instance of entity model E keeps getting reused over and over again (from an Asp.net MVC view) and every time the validation is performed on E the same validator instance gets used.

Because the validator writes to the ErrorMessage property and you can't write to ErrorMessage property more than once, every validation performed after the initial one causes a crash.

Does anyone know how to solve this?

4

1 回答 1

1

尝试为您的验证器提供AttributeUsageAttribute并将AllowMultiple属性设置为 true。

[AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = true)]
class V : ValidationAttribute {    
    public override bool IsValid(object value) {
        //...        
        if (hasErrors)
            ErrorMessage = errorMsg;
        //...        
    }    
}
于 2010-02-15T05:56:26.100 回答