Tuesday, March 18, 2008

Keeping Session Alive With ASP.NET AJAX

I needed to keep session alive as long as a customer is viewing a page, no matter if he/she clicks somewhere on the page. With asp.net ajax, this was very easy.

First, you need a ScriptManager on your page with EnablePageMethods set to true:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
</form>


Second, define in your code behind a simple method that does nothing but keeps session alive like this.

[WebMethod]
[ScriptMethod]
public static void KeepAlive()
{
// just keep session alive
}


Note that you have to use WebMethod and ScriptMethod attributes to make this method avaliable for using in scripts.

Third, you have to define javascript methods to call a page method that is going to keep your session alive.

<script type="text/javascript">
function RegisterKeepAlive( sec )

{
setInterval( "PageMethods.KeepAlive( OnComplete, OnTimeOut, OnError )", sec*1000 );
}
function OnComplete( arg ) {}
function OnTimeOut( arg ){}
function OnError( arg ) {}
</script>


Last, just call RegisterKeepAlive with for example 10 seconds on load event of the body:

<body onload="RegisterKeepAlive( 10 )">

You can also use UpdatePanel with Timer control, but this way is better, because you have more options for processing timeout and errors.

No comments:

eXTReMe Tracker