How can I retrieve session variable stored in a.aspx using Jquery? I have username stored in the session, I need to retrieve the session to display the username in the menu bar. A person login through A.aspx and his details has to be displayed(from database) in B.aspx
1 Answer
One way to handle this would be to create a Web Method or similar within your current page so that you could access the updated value of the Session via an AJAX call :
[WebMethod]
public static string GetSessionValue(string key)
{
return Session[key];
}
Then you could make a POST call via AJAX to request the specific key that you needed (or you could ignore any parameters and simply hard-code the key that you wanted to pull within the method itself) :
public static string GetSessionDisplayName()
{
// Use the name of your Session key here to retrieve your info
return Session["DisplayName"];
}
And then you could use the following jQuery code to pull it with a parameter :
$.ajax({
type: "POST",
url: "YourPage.aspx/GetSessionValue",
data: '{ key: "your-session-key" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// data will hold your Session value, use it here
alert(data);
}
});
Or without one :
$.post('YourPage.aspx/GetSessionDisplayName',function(data){
// data will hold your Session value, use it here
alert(data);
});