セッション変数の設定と取得をする方法

download.gifサンプル コードのダウンロード (PHPtips_Session.msi, 245 KB)

※このサンプルをお使いいただくためには、Visual Studio 2005 が必要です。

サーバー アプリケーションのページ間でデータを共有したい場合には、セッション変数が利用できます。PHP では、session 関数によってセッション変数を作成することができ、従来の ASP や、ASP.NET 2.0 では、session オブジェクトによってセッション変数を使用できます。
PHP では、session_start でセッション変数の使用を開始してから、session_register で変数を登録することでセッション変数が作成されますが、ASP.NET 2.0 では、セッション変数の使用を開始する宣言を行う必要はなく、変数に値を代入するときに登録も行われます。
では、実際にセッション変数を設定してみて、その値を他のページから取得してみましょう。はじめに、TextBox1 という ID を持つテキストボックス コントロールと、Button1 という ID を持つボタン コントロールがあるページを用意します(リスト1)。このページにある [OK] ボタンを押したら、テキストボックス コントロールに入力されている名前を username という名前のセッション変数に設定し、ViewName.aspx にリダイレクトします(リスト2)。

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="InputName.aspx.vb" Inherits="InputName" %>
<!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 runat="server">
    <title>Sample Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         名前<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1"
            runat="server" Text="OK" /></div>
    </form>
</body>
</html>

リスト1.ボタンを押すと入力した名前をセッション変数に設定しリダイレクトする InputName.aspx

Partial Class InputName
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Session("username") = TextBox1.Text
        Response.Redirect("ViewName.aspx")
    End Sub
End Class
Partial Class InputName
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Session("username") = TextBox1.Text
        Response.Redirect("ViewName.aspx")
    End Sub
End Class
 

リスト2.ボタンを押すと入力した名前をセッション変数に設定しリダイレクトする InputName.aspx.vb

session_fig01.gif

図1 サンプル InputName.aspx の表示画面

ViewName.aspx は、Label1 という ID のラベル コントロールを 1 つだけ配置したページで、セッション変数 username が設定されていたら Label1 にメッセージを表示します(リスト3 およびリスト4)。

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ViewName.aspx.vb" Inherits="ViewName" %>
<!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 runat="server">
    <title>Sample Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html

リスト3.セッション変数に設定された名前を表示するページ ViewName.aspx

Partial Class ViewName
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Session("username") Is Nothing Then
            Label1.Text = "ようこそ! " + Session("username").ToString + " さん"
        End If
    End Sub
End Class

リスト4.セッション変数に設定された名前を表示するページ ViewName.aspx.vb

図

図2 サンプル ViewName.aspx の表示画面