Monday, May 19, 2008

Detecting async postback start & end

When you use the UpdatePanel control you probably also want to display some kind of progress bar to the user so they can see when the async. postback starts and when it's done, at least something that indicate that some work are being done and they need to wait until it's done. This can be done by using the UpdateProgress control shipped with ASP.Net Ajax 1.0 Extension. If you use the UpdatePanel control and specify an AsyncPostBackTrigger and also associate the UpdateProgress to an UpdatePanel, the UpdateProgress control will not be displayed.Below is the solution



<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="PleaseWait.aspx.cs"
Inherits="GridViewasInsert" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/
xhtml1-transitional.dtd"
>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">


<asp:ScriptManager ID="s" runat="server">

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


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

<ContentTemplate>
gfdgdg
</ContentTemplate>

<Triggers>
<asp:AsyncPostBackTrigger
ControlID="Button1"
EventName="Click" />
</Triggers>
</asp:UpdatePanel>

<asp:UpdateProgress
AssociatedUpdatePanelID="UpdatePanel1"
ID
="UpdateProgress1" runat="server">
<ProgressTemplate>
Please wait, update in progress
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>


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

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
var postBackElement;

function InitializeRequest(sender, args)
{
if (prm.get_isInAsyncPostBack())
args.set_cancel(true);
postBackElement = args.get_postBackElement();

if (postBackElement.id == 'Button1')
$get('UpdateProgress1').style.display = 'block';
}
function EndRequest(sender, args)
{
if (postBackElement.id == 'Button1')
$get('UpdateProgress1').style.display = 'none';
}
</script>

</body>
</html>

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 GridViewasInsert
: System.Web.UI.Page
{
protected void Page_Load(object sender,
EventArgs e)
{
//Replace This when using on live server
System.Threading.Thread.Sleep(3000);

}
protected void Button1_Click(object sender,
EventArgs e)
{
Response.Redirect("AnotherPage.aspx");
}
}

No comments: