I'm using ASP.NET for a project. I'm trying to set a session variable and access its value in the aspx file.
In VB.NET, I set the session variable like this:
Partial Class MainSite_Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session("TestVariable") = "Lorem ipsum"
End Sub
End Class
And in the corresponding aspx file, I can access its value using <%=Session("TestVariable")%>
.
This works fine. But, now let's say I rewrite this in C#, and try to set the session variable similarly:
public partial class Mainsite_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
Session["TestVariable"] = "Lorem ipsum";
}
}
And once again, in the aspx file, I try to access its value using <%=Session["TestVariable"]%>
.
In this case, Session["TestVariable"]
is null. The value doesn't seem to get assigned. I've also tried changing Session
to HttpContext.Current.Session
with no luck.
Am I setting the session variable wrong in C#?
Interestingly, if I set the session variable in the MasterPageFile, I can then access it in the aspx file. But not if I place it in the Page_Load
method of my Mainsite_Default
class. However, if I set the variable in the Page_Load
method in VB.NET, it works fine.