Introduction
I have developed ASP and ASP.NET sites for many years and one of the most common end user problems (apart from basic stupidity ;-) is that while the user is entering information into a web form or HTML edit box, thesession timeout period will elapse and they lose all the work they have done.
I have tried solutions such as making JavaScript alert the user to click a button or refresh page, but this has restrictions, especially if they are not able to submit the form yet due to required field limitations.
Solution
I recently came across some code which attempted to fix this problem but that was unsuccessful because the author had forgotten the issue of client side caching.
Add to your page the following code:
Collapse |
Copy Codeprivate void Page_Load(object sender, System.EventArgs e)
{
this.AddKeepAlive();
}
Collapse |
Copy Codeprivate void AddKeepAlive()
{
int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 30000;
string str_Script = @<span class='cpp-string'>"
<script type='text/javascript'>
//Number of Reconnects
var count=0;
//Maximum reconnects setting
var max = 5;
function Reconnect(){
count++;
if (count < max)
{
window.status = 'Link to Server Refreshed ' + count.toString()+' time(s)' ;
var img = new Image(1,1);
img.src = 'Reconnect.aspx';
}
}
window.setInterval('Reconnect()',"</span>+ _
int_MilliSecondsTimeOut.ToString()+ @<span class='cpp-string'>"); //Set to length required
</script>
"</span>;
this.Page.RegisterClientScriptBlock("Reconnect", str_Script);
}This code will cause the client to request within 30 seconds of the session timeout the page Reconnect.aspx.
The Important Part
Now this works the first time but if the page is cached locally then the request is not made to the server and the session times out again, so what we have to do is specify that the page Reconnect.aspx cannot be cached at the server or client.
This is done by creating the Reconnect.aspx page with this content:
Collapse |
Copy Code<%@ OutputCache Location="None" VaryByParam="None" %>
<html>
</html>
The OutputCache directive prevents this from being cached and so the request is made each time. No code behind file will be needed for this page so no @Page directive is needed either.
And that's it.
Hope this helps someone.
No comments:
Post a Comment