Real world ASP.Net applications required to have a controlled session time for users. This is done to block unauthorized people from using the application. Nevertheless, you should show users a message that the session is about to expire. In this article I will give you a step-by-step guide on how to display a session timeout message in ASP.Net
Getting Started
1. Open your existing ASP project with Visual Studio
2. Open where you want to display the session timeout. For the purposes I will display the timeout in the master page Navigation Menu, so that I can show it on every page on my application.
3. Since we will be adding the counter to the Site.Master file, first we have to register the Javascript method on the page load event. Open the Site.Master.cs file:
4. Add the following code to the “void Page_Load” function:
if (!IsPostBack) { //set DisplaySessionTimeout() as the startup script of this page Page.ClientScript.RegisterStartupScript(this.GetType(), "onLoad","DisplaySessionTimeout()", true); }
5. Now, open the Site.Master page:
6. Add the following JavaScript code to the <head> of the Site.Master page:
<script type="text/javascript"> var sessionTimeout = "<%= Session.Timeout %>"; function DisplaySessionTimeout() { //assigning minutes left to session timeout to Label document.getElementById("<%= lblSessionTime.ClientID %>").innerText = sessionTimeout; sessionTimeout = sessionTimeout - 1; //if session is not less than 0 if (sessionTimeout >= 0) //call the function again after 1 minute delay window.setTimeout("DisplaySessionTimeout()", 60000); else { //show message box alert("Your current Session is over."); } } </script>
7. Finally, add the following code to the Menu section of the application to display the timer:
<div> <h2>Session time left: <asp:Label ID="lblSessionTime" runat="server"></asp:Label> minutes.</h2> <hr /> <h3>Sample application to display minutes for Session to timeout</h3> </div>
8. And that’s it! We now have a Session Timeout Counter on our ASP Application!
Solution Source provided by Farazsk11
This Concludes Display Session Timeout Counter in ASP.Net
Looking for quality Windows Hosting? Look no further than Arvixe Web Hosting!
Happy Hosting