ASP.Net/Session Cookie/Session Variables

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Add and get value from session (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           Dim myBaz As String = "saved value"
           Session.Add("baz", myBaz)
           Message.Text = Session("baz")
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     <asp:label id="Message" runat="server"/>
  </form>

</body> </html>

      </source>
   
  


Clear session values (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           Session.Clear()
           Message.Text = "There are " & Session.Count & _
              " items in the Session collection."
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     <asp:label id="Message" runat="server"/>
  </form>

</body> </html>

      </source>
   
  


Copy session values (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           If Session.Count > 0 Then
              Dim myArray As Array = Array.CreateInstance(GetType(Object), _
                 Session.Count)
              Session.CopyTo(myArray, 0)
              Message.Text = "The first item in the array is: " & myArray(0)
           End If
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     <asp:label id="Message" runat="server"/>
  </form>

</body> </html>

      </source>
   
  


Get all session keys (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           Dim Key As String
           Message.Text = "Session Keys:"
           For Each Key in Session.Keys
              Message.Text &= "</br>Key:   " & Key
              Message.Text &= "</br>Value:   " & Session(Key)
           Next
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html>

      </source>
   
  


Get Cookie value and assign to the label in C#

   <source lang="csharp">

<%@ Page Language="C#" %> <script runat="server">

   void Page_Load()
   {
       if (Request.Cookies["message"] != null)
           lblCookieValue.Text = Request.Cookies["message"].Value;
   }
   

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Get Cookie</title>

</head> <body>

   <form id="form1" runat="server">
   The value of the message cookie is:
   <asp:Label
       id="lblCookieValue"
       Runat="server" />
   
   </form>

</body> </html>

      </source>
   
  


Get Cookie value (C#)

   <source lang="csharp">

<%@ Page Language="C#" %> <script runat="server">

   void Page_Load()
   {
       if (Request.Cookies["preferences"] != null)
       {
           lblFirstName.Text = Request.Cookies["preferences"]["firstName"];
           lblLastName.Text = Request.Cookies["preferences"]["lastName"];
           lblFavoriteColor.Text = Request.Cookies["preferences"]["favoriteColor"];
       }
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Get Cookie Values</title>

</head> <body>

   <form id="form1" runat="server">
   First Name:
   <asp:Label
       id="lblFirstName"
       Runat="server" />
   
Last Name: <asp:Label id="lblLastName" Runat="server" />
Favorite Color: <asp:Label id="lblFavoriteColor" Runat="server" />
   </form>

</body> </html>

      </source>
   
  


Get session code page in VB (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           Message.Text = "Current Code Page is: " & Session.CodePage
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html>

      </source>
   
  


Get value from session in cross page posting (C#)

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session State</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
       <asp:Button ID="Button1" Runat="server" Text="Store in Session" 
        OnClick="Button1_Click" />
       <asp:HyperLink ID="HyperLink1" Runat="server" 
        NavigateUrl="NextPage.aspx">Next Page</asp:HyperLink>
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page {

   protected void Button1_Click(object sender, EventArgs e)
   {
       Session["mykey"] = TextBox1.Text;
   }

} File: NextPage.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="NextPage.aspx.cs" Inherits="Retrieve" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
   </form>

</body> </html> File: NextPage.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Retrieve : System.Web.UI.Page {

   protected void Page_Load(object sender, EventArgs e)
   {
       string myValue = (string)Session["mykey"];
       Response.Write(myValue);
   }

}

</source>
   
  


Get value from session in cross page posting(VB)

   <source lang="csharp">

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session State</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
       <asp:Button ID="Button1" 
                   Runat="server" 
                   Text="Store in Session" 
                   OnClick="Button1_Click" />
       <asp:HyperLink ID="HyperLink1" 
                      Runat="server" 
                      NavigateUrl="NextPage.aspx">Next Page</asp:HyperLink>
   </form>

</body> </html> File: Default.aspx.vb

Partial Class _Default

   Inherits System.Web.UI.Page
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
       Session("mykey") = TextBox1.Text
   End Sub

End Class File: NextPage.aspx <%@ Page Language="VB" AutoEventWireup="false" CodeFile="NextPage.aspx.vb" Inherits="Retrieve" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
   </form>

</body> </html> File: NextPage.aspx.vb

Partial Class Retrieve

   Inherits System.Web.UI.Page
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       Dim myValue As String = CType(Session("mykey"), String)
       Response.Write(myValue)
   End Sub

End Class

</source>
   
  


Pass variables between pages (VB.net)

   <source lang="csharp">

<%@ Page Language="VB" %> <html>

 <body>
   <%
   Dim Name As String
   Dim Age As String
   Age = 23
   Name = "Sniff"
   %>
   <a href="birthday2.aspx?age=<% Response.Write(Age) %>&name=<%
   Response.Write(Name)%>">click here</a>
 </body>

</html>

<%-- <%@ Page Language="VB" %> <html>

 <body>
     <%
     Dim Name As String
     Dim Age As String
     Name = Request.QueryString("Name")
     Age = Request.QueryString("Age")
     %>

Happy Birthday <% Response.Write(Name) %>

May the next <% Response.Write(Age) %> years be as good!

 </body>

</html>

--%>

      </source>
   
  


Pass variables with & sign (VB.net)

   <source lang="csharp">

<%@ Page Language="VB" %> <html>

 <body>
   <%
   Dim Name As String
   Dim Age As String
   Age = 23
   Name = "Sniff & Jack"
   %>
   <a href="birthday2.aspx?age=<% Response.Write(Age) %>&name=<%
   Response.Write(Name)%>">click here</a>
 </body>

</html>

<%-- <%@ Page Language="VB" %> <html>

 <body>
     <%
     Dim Name As String
     Dim Age As String
     Name = Request.QueryString("Name")
     Age = Request.QueryString("Age")
     %>

Happy Birthday <% Response.Write(Name) %>

May the next <% Response.Write(Age) %> years be as good!

 </body>

</html>

--%>

      </source>
   
  


Remove all session content (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           Session.Contents.RemoveAll()
           Message.Text = "Removed all items from current Session."
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html>

      </source>
   
  


Remove all session values (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           If Session.Count > 0 Then
              Session.RemoveAll()
              Message.Text = "Session collection cleared."
           Else
              Message.Text = "Session collection is already empty."
           End If
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     <asp:label id="Message" runat="server"/>
  </form>

</body> </html>

      </source>
   
  


Remove session value by index (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           If Session.Count > 0 Then
              Session.RemoveAt(0)
              Message.Text = "The item at index 0 was removed."
           Else
              Message.Text = "The item at index 0 does not exist."
           End If
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     <asp:label id="Message" runat="server"/>
  </form>

</body> </html>

      </source>
   
  


Remove value from session value (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           If Not Session("foo") Is Nothing Then
              Session.Remove("foo")
              Message.Text = "Item "foo" was removed."
           Else
              Message.Text = "Item "foo" does not exist."
           End If
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     <asp:label id="Message" runat="server"/>
  </form>

</body> </html>

      </source>
   
  


Session get Message (C#)

   <source lang="csharp">

<%@ Page Language="C#" %> <script runat="server">

   void Page_Load()
   {
       lblMessage.Text = Session["message"].ToString();
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session Get</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Label
       id="lblMessage"
       Runat="server" />
   
   </form>

</body> </html>

      </source>
   
  


Session item count (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           Session("foo") = "Hello, "
           Session("bar") = "World!"
           Message.Text = "The Session collection contains " & _
              Session.Count & " items.</br>"
           Dim I as Integer
           For I = 0 To Session.Count - 1
              Message.Text &= Session(I)
           Next
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html>

      </source>
   
  


Session Set message (C#)

   <source lang="csharp">

<%@ Page Language="C#" %> <script runat="server">

   void Page_Load()
   {
       Session["message"] = "Hello World!";
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session Set</title>

</head> <body>

   <form id="form1" runat="server">

Session item added!

   </form>

</body> </html>

      </source>
   
  


Setting values in session state (C#)

   <source lang="csharp">

<%@ Page Language="C#"

        AutoEventWireup="true"  
        CodeFile="Default.aspx.cs" 
        Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session State</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
       <asp:Button ID="Button1" Runat="server" Text="Store in Session" 
        OnClick="Button1_Click" />
       
<asp:HyperLink ID="HyperLink1" Runat="server" NavigateUrl="Default.aspx">Next Page</asp:HyperLink>
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page {

   protected void Button1_Click(object sender, EventArgs e)
   {
       Session["mykey"] = TextBox1.Text;
   }

}

</source>
   
  


Setting values in session state (VB)

   <source lang="csharp">

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Session State</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
       <asp:Button ID="Button1" Runat="server" Text="Store in Session" 
        OnClick="Button1_Click" />
       <asp:HyperLink ID="HyperLink1" Runat="server" 
        NavigateUrl="Default.aspx">Next Page</asp:HyperLink>
   </form>

</body> </html> File: Default.aspx.vb Partial Class _Default

   Inherits System.Web.UI.Page
   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
       Session("mykey") = TextBox1.Text
   End Sub

End Class

</source>
   
  


Simple session data: set and retrieve

   <source lang="csharp">

<script runat=server> Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)

   If Len(Application("ApplicationName")) = 0 Then
       Application("ApplicationName") = "Check In / " _
           & "Check Out Application"
       Application("PageCount") = 0
   End If
   If Not IsPostBack Then
       Application.Lock
       Application("PageCount") = Application("PageCount") + 1
       Application.UnLock
   End If
   lblTitle.Text = Application("ApplicationName")
   lblCount.Text = "This page has been accessed " _
       & Application("PageCount") & " times."
   Session.TimeOut = 20

End Sub Sub SubmitBtn_Click(Sender As Object, E As EventArgs)

   Session("VisitorsName") = txtVisitorsName.Text
   Response.Redirect("./CheckOut.aspx")

End Sub </SCRIPT> <HTML> <HEAD> <TITLE><% Response.Write(Application("ApplicationName")) %></TITLE> </HEAD> <BODY TEXT="black" LINK="darkred" VLINK="darkred" ALINK="red" LEFTMARGIN="40" TOPMARGIN="60"> <form runat="server"> <asp:Label

   id="lblTitle" 
   BorderWidth="7px"
   BorderStyle=9
   Width="90%"
   Font-Size="25pt"
   Font-Name="Arial"
   runat="server"

/>

<asp:Label

   id="lblMessage1"
   runat="Server"
   Text="Enter Your Name"

/>
<asp:TextBox

   id="txtVisitorsName"
   runat="server"
   MaxLength=50

/>

<asp:button

   id="butOK"
   text="Check In"
   Type="Submit"
   OnClick="SubmitBtn_Click" 
   runat="server"

/>

<%@ Page Language=VB Debug=true %> <asp:Label

   id="lblCount"
   runat="Server"

/> </Form> </BODY> </HTML>

<%-- Global.asax <SCRIPT LANGUAGE="VB" RUNAT="Server"> Sub Application_OnStart

   Application("TaxRate") = 0.5125
   Application("ApplicationName") = "Sample Global.asax"

End Sub Sub Application_OnEnd

   "code that runs when application ends

End Sub Sub Session_OnStart

   Application("SessionStarts") = _
       Application("SessionStarts") + 1
   Session.TimeOut = 1

End Sub Sub Session_OnEnd

   Application("SessionStops") = _
       Application("SessionStops") + 1

End Sub </SCRIPT> --%> <%-- CheckOut.aspx <%@ Page Language=VB Debug=true %> <script runat=server> Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)

   If Len(Session("VisitorsName")) = 0 Then
       lblMessage.Text = "You have not checked in! " _
           & "<A HREF=""./checkin.aspx"">Click here</A>" _
           & " to check in."
       butOK.Visible = False
   Else
       lblMessage.Text = "Your Name: " _
           & Session("VisitorsName") & "
" if Session.IsCookieless Then lblMessage.Text = lblMessage.Text _ & "Your browser does not support cookies.
" else lblMessage.Text = lblMessage.Text _ & "Your browser does support cookies.
" End If lblMessage.Text = lblMessage.Text _ & "Session ID: " & Session.SessionID _ & "
Session Time Out: " & Session.TimeOut _ & " minutes" End If lblTitle.Text = Application("ApplicationName")

End Sub Sub SubmitBtn_Click(Sender As Object, E As EventArgs)

   Session.Abandon
   Response.Redirect("./CheckOut.aspx")

End Sub </SCRIPT> <HTML> <HEAD> <TITLE><% Response.Write(Application("ApplicationName")) %></TITLE> </HEAD> <BODY TEXT="black" LINK="darkred" VLINK="darkred" ALINK="red" LEFTMARGIN="40" TOPMARGIN="60"> <form runat="server"> <asp:Label

   id="lblTitle" 
   BorderWidth="7px"
   BorderStyle=9
   Width="90%"
   Font-Size="25pt"
   Font-Name="Arial"
   runat="server"

/>

<asp:Label

   id="lblMessage"
   runat="Server"
   Text="Enter Your Name"

/>

<asp:button

   id="butOK"
   text="Check Out"
   Type="Submit"
   OnClick="SubmitBtn_Click" 
   runat="server"

/>

</Form> </BODY> </HTML> --%>

      </source>
   
  


Store your Object in Session (C#)

   <source lang="csharp">

<%@ Page language="c#" src="SessionStateExample.aspx.cs" AutoEventWireup="false" Inherits="SessionStateExample" %> <HTML>

 <body>
   <form id="Form1" method="post" runat="server">
     <asp:Label id="lblSession" style="Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 32px" runat="server" Width="232px" Height="61px" Font-Size="Medium" Font-Names="Verdana" Font-Bold="True"></asp:Label>
       <asp:ListBox id="lstItems" style="Z-INDEX: 106; LEFT: 16px; POSITION: absolute; TOP: 16px" runat="server" Width="208px" Height="128px"></asp:ListBox>
       <asp:Button id="cmdMoreInfo" style="Z-INDEX: 106; LEFT: 248px; POSITION: absolute; TOP: 24px" runat="server" Width="120px" Height="24px" Text="More Information"></asp:Button>
<asp:Label id="lblRecord" style="Z-INDEX: 106; LEFT: 248px; POSITION: absolute; TOP: 64px" runat="server" Width="272px" Height="61px" Font-Size="X-Small" Font-Names="Verdana" Font-Bold="True"></asp:Label>
   </form>
 </body>

</HTML>

<%-- using System; using System.Collections; using System.ruponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;

 public class SessionStateExample : System.Web.UI.Page
 {
   protected System.Web.UI.WebControls.Label lblSession;
   protected System.Web.UI.WebControls.ListBox lstItems;
   protected System.Web.UI.WebControls.Button cmdMoreInfo;
   protected System.Web.UI.WebControls.Label lblRecord;
 
   private void Page_Load(object sender, System.EventArgs e)
   {
     if (!this.IsPostBack)
     {
       // Create Product objects.
       Product piece1 = new Product("Econo Sofa", 
         "Acme Inc.", 7.9M);
       Product piece2 = new Product("Pioneer Table", 
         "Heritage Unit", 8.7M);
       Product piece3 = new Product("Retro Cabinet", 
         "Sixties Ltd.", 3.1M);
       // Add objects to session state.
       Session["Product1"] = piece1;
       Session["Product2"] = piece2;
       Session["Product3"] = piece3;
       // Add rows to list control.
       lstItems.Items.Clear();
       lstItems.Items.Add(piece1.Name);
       lstItems.Items.Add(piece2.Name);
       lstItems.Items.Add(piece3.Name);
     }
     // Display some basic information about the session.
     // This is useful for testing configuration settings.
     lblSession.Text = "Session ID: " + Session.SessionID;
     lblSession.Text += "
Number of Objects: "; lblSession.Text += Session.Count.ToString(); lblSession.Text += "
Mode: " + Session.Mode.ToString(); lblSession.Text += "
Is Cookieless: "; lblSession.Text += Session.IsCookieless.ToString(); lblSession.Text += "
Is New: "; lblSession.Text += Session.IsNewSession.ToString(); lblSession.Text += "
Timeout (minutes): "; lblSession.Text += Session.Timeout.ToString(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cmdMoreInfo.Click += new System.EventHandler(this.cmdMoreInfo_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmdMoreInfo_Click(object sender, System.EventArgs e) { if (lstItems.SelectedIndex == -1) { lblRecord.Text = "No item selected."; } else { // Construct the right key name based on the index. string key = "Product" + (lstItems.SelectedIndex + 1).ToString(); // Retrieve the Product object from session state. Product piece = (Product)Session[key]; // Display the information for this object. lblRecord.Text = "Name: " + piece.Name; lblRecord.Text += "
Manufacturer: "; lblRecord.Text += piece.Description; lblRecord.Text += "
Cost: $" + piece.Cost.ToString(); } } }
 public class Product
 {
   public string Name;
   public string Description;
   public decimal Cost;
   public Product(string name, string description, 
     decimal cost)
   {
     Name = name;
     Description = description;
     Cost = cost;
   }
 }


--%>

      </source>
   
  


Use Session item (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <script runat="server">
        Sub Page_Load()
           Session.Item("foo") = "foo"
           Session.Item("foo2") = "foo2"
           Message.Text = Session.Item("foo") & "</br>"
           Message.Text &= Session.Item(1)
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html>

      </source>
   
  


Use session to store action time (VB.net)

   <source lang="csharp">

<%@ Page Language="VB" %> <script runat="server">

   Sub Page_Load()
       If Not Page.IsPostBack Then
           ResetStartTime()
       End If
   End Sub
   
   Protected Sub btnAgain_Click(ByVal sender As Object, ByVal e As System.EventArgs)
       ResetStartTime()
   End Sub
   
   Sub ResetStartTime()
       Session("StartTime") = DateTime.Now
   End Sub
   
   
   Protected Sub valAnswer_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
       Dim startTime As DateTime = CType(Session("StartTime"), DateTime)
       If startTime.AddSeconds(5) > DateTime.Now Then
           args.IsValid = True
       Else
           args.IsValid = False
       End If
   End Sub

</script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Timed Test</title>

</head> <body>

   <form id="form1" runat="server">

You have 5 seconds to answer the following question:

   <asp:Label
       id="lblQuestion"
       Text="What was Aristotle"s first name?"
       AssociatedControlID="txtAnswer"
       Runat="server" />
   
<asp:TextBox id="txtAnswer" Runat="server" /> <asp:CustomValidator id="valAnswer" Text="(You answered too slowly!)" OnServerValidate="valAnswer_ServerValidate" Runat="server" />

<asp:Button id="btnSubmit" Text="Submit" Runat="server" /> <asp:Button id="btnAgain" Text="Try Again!" CausesValidation="false" OnClick="btnAgain_Click" Runat="server" />
   </form>

</body> </html>

      </source>
   
  


Use session variables (VB.net)

   <source lang="csharp">

<%@ Page language="VB"%> <script language="vb" runat="server">

 Sub EmptyClick(sender As System.Object, e As System.EventArgs)
   Session("BasketCount") = 0
 End Sub
 Sub AddClick(sender As System.Object, e As System.EventArgs)
   Session("BasketCount") += 1
 End Sub

</script> <html>

 <body>
   <form id="BasketForm" method="post" runat="server">
     <asp:Button id="Empty" OnClick="EmptyClick" runat="server" Text="Empty"/>
     
<asp:Button id="Add" OnClick="AddClick" runat="server" Text="Add"/>
Basket items : <%=Session("BasketCount")%>
</form> </body>

</html>

      </source>
   
  


Write value to session (VB.net)

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Writing to Session in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Session("foo") = "Hello, World!"
           Message.Text = "Wrote the value "Hello, World" to a Session item named "foo"."
        End Sub
     </script>
  </head>

<body>

  <asp:label id="Message" runat="server"/>

</body> </html>

      </source>