6.2. Maintaining Information about a User Throughout a Session

Problem

You want to make personalized information available to the users of your application for as long as each remains active, without having to access a database each time the information is needed and regardless of the number of pages traversed.

Solution

Create a class in which to store the personalized data, instantiate the class and load the data, store the data object in the Session object, and then access the data from the Session object as required.

In the code-behind class for your ASP.NET pages that need access to the data, use the .NET language of your choice to:

  1. Check to see if the object used to store the personalized data exists in the Session object.

  2. If the object exists, retrieve the object from Session. If the object does not exist, instantiate the class used for the personalized data and store it in the Session object.

  3. Use the data as required in your application.

A simple example that illustrates this solution is shown in Examples Example 6-6 through Example 6-10. The example uses the class shown in Example 6-6 (CH06PersonalDataVB for VB) and Example 6-7 (CH06PersonalDataCS for C#) to provide a container for some simple personalization data. This class contains properties for each of the data items and a default constructor.

Figure 6-2 shows a simple form that we’ve created for viewing the current contents of the personalization data stored in the Session object and for entering new session state data ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.