Wednesday, November 7, 2007

Ajax UpdatePanel (19) endRequest Event


<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="5_HandleResponse.aspx.cs" Inherits="_5_HandleResponse" Title="HandleResponse" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

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

<ContentTemplate>

<%= DateTime.Now %><br />

<asp:Button ID="btnError" runat="server" Text="Error" OnClick="btnError_Click" />

<asp:Button ID="btnTimeout" runat="server" Text="Timeout" OnClick="btnTimeout_Click" />

<input type="button" value="Abort" onclick="Sys.WebForms.PageRequestManager.getInstance().abortPostBack();" />

<asp:Button ID="btnDataItem" runat="server" Text="Register DataItem" OnClick="btnDataItem_Click" />

</ContentTemplate>

</asp:UpdatePanel>

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

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(

function(sender, e)

{

if (e.get_error())

{

e.set_errorHandled(true);

if (e.get_response().get_timedOut())

{

showMessage("Request time out!");

}

else if (e.get_response().get_statusCode() != 200)

{

showMessage("Unknown error!");

}

else

{

showMessage(e.get_error().message);

}

}

else if (e.get_response().get_aborted())

{

showMessage("Request aborted!");

}

else

{

var upId = "<%= this.UpdatePanel1.ClientID %>";

var item = e.get_dataItems()[upId];

showMessage("You have registered: " + item);

}

});

</script>

</asp:Content>



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;

using System.Threading;

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

{

protected void Page_Load(object sender, EventArgs e)

{

ScriptManager.GetCurrent(this).AsyncPostBackTimeout = 3;

}

protected void btnError_Click(object sender, EventArgs e)

{

int two = 2;

int i = 3 / (two - 2);

}

protected void btnTimeout_Click(object sender, EventArgs e)

{

Thread.Sleep(5000);

}

protected void btnDataItem_Click(object sender, EventArgs e)

{

ScriptManager.GetCurrent(this).RegisterDataItem(this.UpdatePanel1, DateTime.Now.ToString());

}

}

In this code, we used the endRequest Event to handle errors which is pretty standard.

blog comments powered by Disqus