Monday, October 29, 2007

Ajax UpdatePanel (12) Error Handling 1

<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server" AllowCustomErrorsRedirect="false" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError">

</asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

</ContentTemplate>

</asp:UpdatePanel>

<div id="error"></div>

<script type="text/javascript" language="javascript">

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, e)

{

e.set_errorHandled(true);

$get("error").innerHTML = "Sorry, an error has occurred: " + e.get_error().message;

setTimeout(function(){ $get("error").innerHTML = ""; }, 3000);

});

</script>

</form>



using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class Demo6_2_CatchError : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

throw new Exception("Custom Error!");

}

protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)

{

ScriptManager.GetCurrent(this).AsyncPostBackErrorMessage = e.Exception.Message;

}

}

In this code, when Button1 is clicked, the client side javascript will handle the exception, then the div will show the error message for 3 seconds.

blog comments powered by Disqus