views:

211

answers:

2

Hi All,
I am creating a web application using ASP.Net. I am using session in my application.
There is one scenario where I am trying to access session variable through Javascript. It is working fine, when I m accessing it in normal state. But after session expiry, if click on any button, it throws exception and behaves abnormally, resulting in page not found.
Here is the code I am using;

 var TransactionID = '<% =((Hashtable)(Session["SessionData"]))["TransactionID "] %>';
 if(TransactionID !='')
 {
    //action
 }

I am trying to achieve something like of sort in c#;

String lsStr;
if(null != lsStr)
{
    //action
}

Please help me, if anyone knows how to check if session exists or not using javascript.
Thanks in advance.

A: 

The suggestion to put this check in a timer client side would extend the session every time it ran causing the session never to expire, Only do this if this is the desired functionality.

The best bet is to perform the check only when you need to by doing an ajax request to a page that doesn't require authentication that page could then test if a certain session variable exists and return true or false.

As an example an application I recently worked on had a page with client side logic that required checks to make sure the session still existed. In this case for that page I knew the userID was always stored in Session["UserID"] so I created a c# ajax page that just returned false if this object was null and true if it existed this allowed me to calls this page from JavaScript and tell if the session had expired. This will probably need to be changed a bit to fit your situation but I'm sure you could do something using the same logic.

Gavin Draper
+1  A: 

Hey,

I would recommend a public property in your code-behind page that does:

public string TransactionID
{
   get { 
        var data = ((Hashtable)(Session["SessionData"])); 
        if (data != null)
           return data["TransactionID "];
        else
           return null;
   }
}

To get around the immediate error. If you want a polling mechanism to know when it expires, consider the JS timer countdown/AJAX call to the server idea. There is no way to check session from the client without requesting information from the server.

But, using the property above, when the page posts back, and on the client the transaction ID JS variable would be null, that would be a way of identifying that the Session expired too.

HTH.

Brian
Thanks Brian :)I was thinking about hiddenVariable. so that, there would be no need to access code behind property.Is it secure to use hidden variables ?
Vijay Balkawade
Hidden variables are rendered directly on the screen. If you have an expectation of privacy with the transaction ID, hidden variables are not secure, but to make it secure you can encrypt the key and store the encrypted value there.
Brian