开发者

Linq to Entity Model's DataAnnotations don't reset

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?


Try giving your validator the AttributeUsageAttribute and setting the AllowMultiple property to true.

[AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = true)]
class V : ValidationAttribute {    
    public override bool IsValid(object value) {
        //...        
        if (hasErrors)
            ErrorMessage = errorMsg;
        //...        
    }    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜