ASP.NET Tutorial/Sessions/Session Variables — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 15:30, 26 мая 2010
Содержание
- 1 A session-aware base page
- 2 Look for Variables
- 3 Retrieve the value of an item that you have stored in Session state.
- 4 Save value in text box to session and read it back (VB.net/C#)
- 5 Save value to session object and read them back (VB.net)
- 6 Session counter and application counter (C#)
- 7 Session counter and application counter (VB)
- 8 Setting and retrieving objects from the Session using State Service and a base page (C#)
- 9 Setting and retrieving objects from the Session using State Service and a base page (VB)
- 10 Sorting a DataView stored in Session state.
- 11 Store user defined object in Session (C#)
- 12 Using Session State
A session-aware base page
C# version
using System;
using System.Web;
public class SmartSessionPage : System.Web.UI.Page
{
private const string MYKEY = "mykey";
public string MyKey
{
get
{
return (string)Session[MYKEY];
}
set
{
Session[MYKEY] = value;
}
}
}
VB version
Imports Microsoft.VisualBasic
Imports System
Imports System.Web
Public Class SmartSessionPage
Inherits System.Web.UI.Page
Private Const MYSESSIONKEY As String = "mykey"
Public Property MyKey() As String
Get
Return CType(Session(MYSESSIONKEY), String)
End Get
Set(ByVal value As String)
Session(MYSESSIONKEY) = value
End Set
End Property
End Class
Look for Variables
<% @ Page Language="VB" %>
<html>
<head>
<title>Look for Variables</title>
</head>
<body>
<center><h1>Look for Session and Application Variables</h1></center><hr/>
<%
Dim Book, Chapter, Publisher, Author As String
Book = Session("Book")
Chapter = Session("Chapter")
Publisher = Application("Publisher")
Author = Application("Author")
If (Book = Nothing) Then
Response.Write("Book: Unknown <br/>")
Else
Response.Write("Book: " & Book & "<br/>")
End If
If (Chapter = Nothing) Then
Response.Write("Chapter: Unknown <br/>")
Else
Response.Write("Chapter: " & Chapter & "<br/>")
End If
If (Publisher = Nothing) Then
Response.Write("Publisher: Unknown <br/>")
Else
Response.Write("Publisher: " & Publisher & "<br/>")
End If
If (Author = Nothing) Then
Response.Write("Author: Unknown <br/>")
Else
Response.Write("Author: " & Author & "<br/>")
End If
%>
</body>
</html>
Retrieve the value of an item that you have stored in Session state.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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">
<div>
<asp:Label
id="lblMessage"
Runat="server" />
</div>
</form>
</body>
</html>
Save value in text box to session and read it back (VB.net/C#)
<%@Page Language="VB" %>
<script runat="server">
sub Submit_Click(Sender as Object,e as EventArgs)
if tbName.Value <>""
Session("Name ")=tbName.Value
Response.Write("Hi " & Session("Name ")&"!")
else
Response.Write("You forgot to enter a name.")
end if
end sub
</script>
<html>
<body>
<form runat="server">
Please enter your name:
<input type="text" id="tbName" runat="server"/>
<asp:Button id="btSubmit" text="Submit" runat="server" OnClick="Submit_Click" />
</form>
</body>
</html>
////////////////////////////
<%@ Page Language="VB" %>
<script runat="server">
sub Page_Load(Sender as Object,e as EventArgs)
Label1.Text ="Welcome back " & Session("Name ") & "!"
end sub
</script>
<html><body>
<form runat="server">
<asp:Label id="Label1" runat="server"/>
</form>
</body></html>
/////////////////////////////
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(Object Sender, EventArgs e) {
Label1.Text = "Welcome back " + Session["Name"] + "!";
}
</script>
<html><body>
<form runat="server">
<asp:Label id="Label1" runat="server"/>
</form>
</body></html>
Save value to session object and read them back (VB.net)
<%@Page Language="VB" %>
<script runat="server">
sub Page_Load(Sender as Object,e as EventArgs)
dim strVariable as string
Session("Name")="A "
Session("FavoriteColor")="Blue "
Session("EyeColor")="Brown "
Session("AMessage")="Welcome to my world "
Session("ASPNET")="asp.net "
for each strVariable in Session.Contents
Label1.Text +="<b>" & strVariable &"</b>:" & _
Session(strVariable)&"<br>"
next
end sub
</script>
<html><body>
<form runat="server">
<asp:Label id="Label1" runat="server"/>
</form>
</body></html>
Session counter and application counter (C#)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Chapter 8: Counter</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblSessionClicks" runat="server"></asp:Label><br />
<br />
<asp:Label ID="lblApplicationClicks" runat="server"></asp:Label><br />
<br />
<asp:Button ID="btnPost" runat="server" OnClick="btnPost_Click" Text="Post" /> </div>
</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
{
int sessionCount;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Count"] == null)
{
sessionCount = 0;
}
else
{
sessionCount = Convert.ToInt32(Session["Count"]);
}
}
protected void btnPost_Click(object sender, EventArgs e)
{
sessionCount++;
Session["Count"] = sessionCount;
lblSessionClicks.Text = "You have clicked the button " + sessionCount + " times.";
Application.Lock();
int applicationCount = Convert.ToInt32(Application["HitCount"]);
applicationCount++;
Application["HitCount"] = applicationCount;
Application.UnLock();
lblApplicationClicks.Text = "All users have clicked the button " + applicationCount + " times.";
}
}
File: Global.asax
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application.Add("HitCount", 0);
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>
Session counter and application counter (VB)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!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>Chapter 8: Counter</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblSessionClicks" runat="server"></asp:Label><br />
<br />
<asp:Label ID="lblApplicationClicks" runat="server"></asp:Label><br />
<br />
<asp:Button ID="btnPost" runat="server" Text="Post" /> </div>
</form>
</body>
</html>
File: Default.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page
Dim iSessionCount As Integer
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Session("Count") Is Nothing Then
iSessionCount = 0
Else
iSessionCount = CType(Session("Count"), Integer)
End If
End Sub
Protected Sub btnPost_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPost.Click
iSessionCount += 1
lblSessionClicks.Text = "You have clicked the button " & iSessionCount & " times."
Application.Lock()
Dim iApplicationCount As Integer = CType(Application("HitCount"), Integer)
iApplicationCount += 1
Application("HitCount") = iApplicationCount
Application.UnLock()
lblApplicationClicks.Text = "All users have clicked the button " & iApplicationCount & " times."
End Sub
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Session("Count") = iSessionCount
End Sub
End Class
File: Global.asax
<%@ Application Language="VB" %>
<script runat="server">
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
" Code that runs on application startup
Application.Add("HitCount", 0)
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
" Code that runs on application shutdown
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
" Code that runs when an unhandled error occurs
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
" Code that runs when a new session is started
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
" Code that runs when a session ends.
" Note: The Session_End event is raised only when the sessionstate mode
" is set to InProc in the Web.config file. If session mode is set to StateServer
" or SQLServer, the event is not raised.
End Sub
</script>
Setting and retrieving objects from the Session using State Service and a base page (C#)
<%@ 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">
<div>
<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
<asp:Button ID="Button1" Runat="server" Text="Store in Session"
OnClick="Button1_Click" />
<br />
<asp:HyperLink ID="HyperLink1" Runat="server"
NavigateUrl="NextPage.aspx">Next Page</asp:HyperLink>
</div>
</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 : SmartSessionPage
{
protected void Button1_Click(object sender, EventArgs e)
{
string[] names = TextBox1.Text.Split(" ");
Person p = new Person();
p.firstName = names[0];
p.lastName = names[1];
Session["myperson"] = p;
}
}
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">
<div>
</div>
</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;
[Serializable]
public class Person
{
public string firstName;
public string lastName;
public override string ToString()
{
return String.Format("Person Object: {0} {1}", firstName, lastName);
}
}
public class SmartSessionPage : System.Web.UI.Page
{
private const string MYPERSON = "myperson";
public Person MyPerson
{
get
{
return (Person)Session[MYPERSON];
}
set
{
Session[MYPERSON] = value;
}
}
}
public partial class Retrieve : SmartSessionPage
{
protected void Page_Load(object sender, EventArgs e)
{
Person p = MyPerson;
Response.Write(p); //ToString will be called!
}
}
Setting and retrieving objects from the Session using State Service and a base page (VB)
<%@ 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">
<div>
<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
<asp:Button ID="Button1" Runat="server" Text="Store in Session"
OnClick="Button1_Click" />
<br />
<asp:HyperLink ID="HyperLink1" Runat="server"
NavigateUrl="NextPage.aspx">Next Page</asp:HyperLink>
</div>
</form>
</body>
</html>
File: Default.aspx.vb
Partial Class _Default
Inherits SmartSessionPage
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim names As String()
names = TextBox1.Text.Split(" "c) " " "c creates a char
Dim p As New Person()
p.firstName = names(0)
p.lastName = names(1)
Session("myperson") = p
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">
<div>
</div>
</form>
</body>
</html>
File: NextPage.aspx.vb
Imports Microsoft.VisualBasic
Imports System
Imports System.Web
Partial Class Retrieve
Inherits SmartSessionPage
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim p As Person = MyPerson
Response.Write(p) " ToString will be called!
End Sub
End Class
<Serializable()> _
Public Class Person
Public firstName As String
Public lastName As String
Public Overrides Function ToString() As String
Return String.Format("Person Object: {0} {1}", firstName, lastName)
End Function
End Class
Public Class SmartSessionPage
Inherits System.Web.UI.Page
Private Const MYSESSIONPERSONKEY As String = "myperson"
Public Property MyPerson() As Person
Get
Return CType(Session(MYSESSIONPERSONKEY), Person)
End Get
Set(ByVal value As Person)
Session(MYSESSIONPERSONKEY) = value
End Set
End Property
End Class
Sorting a DataView stored in Session state.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
DataView dvProducts;
void Page_Load()
{
dvProducts = (DataView)Session["Products"];
if (dvProducts == null)
{
string conString = WebConfigurationManager.ConnectionStrings["Products"]. ConnectionString;
SqlDataAdapter dad = new SqlDataAdapter("SELECT Id,Title,Director FROM Products", conString);
DataTable dtblProducts = new DataTable();
dad.Fill(dtblProducts);
dvProducts = new DataView(dtblProducts);
Session["Products"] = dvProducts;
}
}
protected void grdProducts_Sorting(object sender, GridViewSortEventArgs e)
{
dvProducts.Sort = e.SortExpression;
}
void Page_PreRender()
{
grdProducts.DataSource = dvProducts;
grdProducts.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Session DataView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView
id="grdProducts"
AllowSorting="true"
EnableViewState="false"
OnSorting="grdProducts_Sorting"
Runat="server" />
<br />
<asp:LinkButton
id="lnkReload"
Text="Reload Page"
Runat="server" />
</div>
</form>
</body>
</html>
Store user defined object in Session (C#)
File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SessionStateExample" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label id="lblSession"
runat="server"
Width="472px"
Font-Size="Medium"
Font-Names="Verdana"
Font-Bold="True"></asp:Label>
<br /><br />
<div >
<table>
<tr>
<td>
<asp:ListBox id="lstItems"
Width="208px"
Height="128px"
runat="server"></asp:ListBox>
</td>
<td style="padding: 10px">
<asp:Button id="cmdMoreInfo"
Width="120px"
Text="More Information"
runat="server"
OnClick="cmdMoreInfo_Click"></asp:Button>
<br />
<br />
<asp:Label id="lblRecord"
runat="server"
Width="272px"
Font-Size="Small"
Font-Names="Verdana"
Font-Bold="True"></asp:Label>
</td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
File: Default.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 SessionStateExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Product piece1 = new Product("A","A Inc.", 7.9M);
Product piece2 = new Product("B","B Inc.", 6.5M);
Product piece3 = new Product("C","C Ltd.", 3.1M);
Session["Product1"] = piece1;
Session["Product2"] = piece2;
Session["Product3"] = piece3;
lstItems.Items.Add(piece1.Name);
lstItems.Items.Add(piece2.Name);
lstItems.Items.Add(piece3.Name);
}
lblSession.Text = "Session ID: " + Session.SessionID;
lblSession.Text += "<br />Number of Objects: ";
lblSession.Text += Session.Count.ToString();
lblSession.Text += "<br />Mode: " + Session.Mode.ToString();
lblSession.Text += "<br />Is Cookieless: ";
lblSession.Text += Session.IsCookieless.ToString();
lblSession.Text += "<br />Is New: ";
lblSession.Text += Session.IsNewSession.ToString();
lblSession.Text += "<br />Timeout (minutes): ";
lblSession.Text += Session.Timeout.ToString();
}
protected void cmdMoreInfo_Click(object sender, EventArgs e)
{
if (lstItems.SelectedIndex == -1)
{
lblRecord.Text = "No item selected.";
}
else
{
string key = "Product" +(lstItems.SelectedIndex + 1).ToString();
Product piece = (Product)Session[key];
lblRecord.Text = "Name: " + piece.Name;
lblRecord.Text += "<br />Manufacturer: ";
lblRecord.Text += piece.Description;
lblRecord.Text += "<br />Cost: " + piece.Cost.ToString("c");
}
}
}
class Product
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
private decimal cost;
public decimal Cost
{
get { return cost; }
set { cost = value; }
}
public Product(string name, string description,
decimal cost)
{
Name = name;
Description = description;
Cost = cost;
}
}
Using Session State
Items stored in Session state are scoped to a particular user.
You use Session state to store user preferences or other user-specific data across multiple page requests.
Session state has no size limitations.
Session state can represent more complex objects than simple strings of text.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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">
<div>
<h1>Session item added!</h1>
</div>
</form>
</body>
</html>