다음을 통해 공유


Storing and Removing Data from the ASP Session Object

The Session object provides a dynamic, associative array into which you can store information. You can store scalar variables and object variables into the Session object.

To store a variable in the Session object, assign a value to a named entry in the Session object. For example, the following command stores two new variables in the Session object:

<%  
  Session("FirstName") = "Jeff" 
  Session("LastName") = "Smith"  
%> 

To retrieve information from the Session object, access the named entry. For example, to display the current value of Session("FirstName"):

Welcome <%= Session("FirstName") %> 

You can store user preferences in the Session object, and then access that preference to determine what page to return to the user. For example, you can allow a user to specify a text-only version of your content in the first page of the application and apply this choice on all subsequent pages that the user visits in this application.

<% If Session("ScreenResolution") = "Low" Then %>  
  This is the text version of the page. 
<% Else %>  
  This is the multimedia version of the page. 
<% End If %> 

You can also store an object instance in the Session object, although doing so can affect server performance. For more information, see Setting Object Scope.

At times, it may be desirable to delete items stored in the Session object. For example, it is not uncommon for users visiting an online retail store to change their minds, abandon a list of purchase items, and decide on a completely different set of selections. In such a case it may be expedient to update the Session object by deleting inappropriate values.

The Session object's Session.Contents Collection collection contains all of the variables that have been stored (that is, those stored without using the HTML <OBJECT> tag) for a session. By using the Contents collection's Session.Contents.Remove method, you can selectively remove a reference to a variable that was added for the session state. The following script illustrates how to use the Remove method to purge an item, in this case user discount information, from the Session object:

<% 
  If Session.Contents("Purchamnt") <= 75 then  
    Session.Contents.Remove("Discount") 
  End If  
%> 

If desirable, you can also use the Contents collection's Session.Contents.RemoveAll method to completely remove all variables stored for the session:

Session.Content.RemoveAll() 

Using the Remove method you can choose to delete items by name or by index. The following script demonstrates how to cycle through values stored in the Session object and conditionally remove values by index:

<% 
  For Each intQuote in Session.Contents 
    If Session.Contents(intQuote) < 200 Then 
      Session.Contents.Remove(intQuote)   
    End If 
  Next 
%>