There is a nice control in ASP.NET called ValidationSummary. Its purpose is to group and display all validation error messages in one place. Errors reported by Validator controls put on the page are displayed there. This is a standard way we all use ValidationSummary. Sometimes however, there is a need for presenting some kind of error found on the server side.
After investigation, I have found that there is no easy way of adding errors to the ValidationSummary. That is because the ValidationSummary control reads error messages directly from the page by means of iteration over all validators it gets by calling Page.GetValidators() method. Since none of the crucial methods is virtual, there is no way of customizing the standard behavior by means of inheritance.
This time rather than fighting/hacking ASP.NET once again, I've decided, to use it's own weapons against it. It came out as a rather clean solution. In order to add your error message to a ValidationSummary control you can add a validator to a Validators collection of the page. But which one to use? None of the standard ones since they all inherit from a Label (!?!?!).
It comes out, that ValidatorCollection's (that is the type of Validators property) Add method is one of those few .NET methods that operates using interfaces rather than concrete classes. This particular method accepts an IValidator interface. What we need then is a special CustomError class that looks like this:
public class CustomError : IValidator
{
private string errorMessage;
public CustomError(string errorMessage)
{
this.errorMessage = errorMessage;
}
public string ErrorMessage
{
get
{
return errorMessage;
}
set
{
throw new NotSupportedException();
}
}
public bool IsValid
{
get
{
return false;
}
set
{
throw new NotSupportedException();
}
}
public void Validate()
{ }
}
Now using this class is dead simple. Once we need to add an error to the summary, we do the following:
Validators.Add(new CustomError("Error Message"));
The only problem is that if the error is to persist between postbacks, we have to add the new validator every time.