15 Jul
2004

Client Side ASP.Net Errors

I have always been bothered by needing to layout
my error reporting with an asp:Label and then filling out the Tet property in red
or something. I would prefer a windows style feedback like a Messagebox. So,
extending Matt
Berther
‘s idea of base classes for ASP.Net pages, I added the following function
to my base class.

protected> void ThrowClientSideError( string errorMessage
){
        string err = “<script
language=’JavaScript’>alert(‘”
+ errorMessage + “‘);</script>”;
        if (!Page.IsStartupScriptRegistered(“clientScript”))
{
               
Page
.RegisterStartupScript(“clientScript”,
err);
         }
}

Which allows me to call thusly from my code behind page:

ThrowClientSideError(
“You have done something stupid.” );>

Which results in:

This technique allows you to leave your page design alone for handing
error feedback without sending the user to a different page. This means that they
do not loose state on the form that they may be filling out. It does require a postback
for the alert to fire, but so would filling out a label or redirecting to an error
page. For a genuine application error, I still handle it globally and print a stack
trac for debugging.