If you ever used ASP.NET Ajax and UpdatePanels you must have seen the annoying alert window that pops up when error occurres during Ajax request. Since WebFu event where Milica and I presented ASP.NET Ajax, many developers asked us how to "kill" this popup window.
I'm going to show you two simple ways to kill the popup window forever. Note: You can find the complete source code in the attachment.
Let's say we have two buttons inside the UpdatePanel. One that will perform a successful Ajax postback and render the current time, and one that will cause an error. We also have a div (divError) that will display the error message if one occurres. Don't remember that we need a ScriptManager on every Ajax-enabled web page. The code below shows this case.<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<div id="divError" class="Error">
<asp:Image ID="Image1" runat="server"
ImageUrl="~/error_16x16.gif" ImageAlign="AbsMiddle" />
Oooooops, <div id="divMessage" class="Message"></div>
<asp:Button ID="Button2" runat="server"
Text="Create successful Ajax PostBack" OnClick="Button2_Click" />
<asp:Button ID="Button1" runat="server"
Text="Create Exception!" OnClick="Button1_Click" />
<asp:Label ID="lblDateTime" runat="server"></asp:Label>
Now let's see what is happening on the server. Request that performs a successful Ajax postback will render the time in a label. The other one will throw generic Exception.
protected void Button1_Click(object sender, EventArgs e)
throw new Exception("Exception generated on server occurred!");
protected void Button2_Click(object sender, EventArgs e)
lblDateTime.Text = "The last Ajax PostBack occurred at " +
Handling exceptions using ScriptManager events
We can use some of ScriptManager functionality to handle exceptions in ASP.NET Ajax postbacks. Let's change slightly the example above. We'll define OnAsyncPostBackError handler in the definition of ScriptManager.
<asp:ScriptManager ID="ScriptManager1" runat="server"
On the server, we'll get the Exception message from AsyncPostBackErrorEventArgs class and pass it to the ScriptManager.
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message;
All other code will be the same as in the example above.
You can find the source code in the attachment.