Adding server side errors to Summary Control

“Validation Summary” is very handy to use when one is using the ASP.NET validation controls. We can make it more useful by adding sever side errors to it, it is bit trick but not impossible. By doing this one can avoid the overhead of adding label displaying the server side errors on the page.

All validation controls implements the IValidator interface and add themselves to the Page.Validators collection at page creation time. IValidator has three important members: IsValid, ErrorMessage and Validate(). When validation occurs, the Validate() method of each control is called which in turn sets the IsValid and ErrorMessage property. At render time the ValidationSummary cycles through the Validators collection and looks for controls where IsValid is set to false. If that's the case, the value of the ErrorMessage property is rendered to the summary.

Since IValidator is abstract interface so it better to use BaseValidator class whose functionality is same as of  IValidator interface.

To add a new error message, you simply have to add an BaseValidator derived class to the Validators collection (with IsValid = false) and let the summary pick it up. The following small helper class accomplishes that:

// adds an error message to a ValidationSummary control

public class ErrorSummary : BaseValidator
{

public static void AddError(string message, Page page)
{
AddError(message, string.Empty, page);
}

public static void AddError(string message, string validationGroup, Page page)
{
ErrorSummary error = new ErrorSummary(message,validationGroup);
page.Validators.Add(error);
}

private ErrorSummary(string message, string validationGroup)
{
ErrorMessage = message;
ValidationGroup = validationGroup;
base.IsValid = false;
}

public new bool IsValid
{
get { return base.IsValid; }
}

public new void Validate()
{
base.IsValid = EvaluateIsValid();
}
protected override bool EvaluateIsValid()
{
return false;
}
}
You can use the class in your code like that:

catch (Exception ex)

{

    // logging

 

    ErrorSummary.AddError("error message", this);

    return;

}

Print | posted on Monday, August 17, 2009 3:01 PM

Feedback

# re: Adding server side errors to Summary Control

Left by Tien Do at 8/19/2009 12:34 PM
Gravatar Thank you very much!
Good trick.

Your comment:





 
 

Copyright © BackToBasics

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski