ASP.
NET State
Management
Anand.P.K
1
State Management
• We are working in a connectionless environment
• Which means we can’t use normal variables to persist data between
server round trips, and pages.
• Instead we have a range of techniques provided by Asp.Net and
HTTP that we can use:
2
State Management
• Between Server Round • In A Session
Trips • Session Variables
• ViewState • Cookies
• Hidden form fields • Between Sessions
• Querystrings • Cookies(with expiry)
• HTML Forms • Database or other storage
• Between Pages • Application
• Querystrings • ApplicationVariable
• Server.Transfer and • Cache Object
Context.Items • appSettings in Web.Config
• Cookies
• HTML Forms
3
ViewState
• ASP.Net mechanism to persist data through server
round trips on a single page.
• All ASP controls (including the Page object) have
EnableViewState property that is defaulted to true
• You can add your own data to view state using :
[c#] ViewState.Add("MyVariable”,MyValue);
vb] ViewState.Add(“MyVariable”,MyValue)
• ViewState materializes as a hidden field in the HTML
output, with all the ViewState values encoded to
ensure they come from the page that created them.
4
HTML Forms
• Since ASP.NET requires a HTML Form that posts back to
itself, and you can't nest forms in HTML this technique is
limited.
• However you could add a normal HTML form below the
ASP.NET form and post to a different page from that.
• Or you can add normal HTML form elements (such as a
TextField) inside the ASP.NET form
• Then you can retreive these values using the Request.Form
collection:
[c#] MyValue = Request.Form["MyVariable"];
[vb] MyValue = Request.Form("MyVariable“)
5
Querystrings
•Querystring can pass data from one
page to another, even across web sites
and servers.
•Can by simple a URL in a hyperlink:
<A
href="anotherpage.aspx?MyVariable=MyV
alue&MyOtherVariable=MyOtherValue">Cl
ick me</a>
6
QueryStrings
• Or you could use a redirect in code:
[c#]
Response.Redirect("
anotherpage.aspx?MyVariable=MyValue&M
yOtherVariable=MyOtherValue");
[vb] Response.Redirect("
anotherpage.aspx?MyVariable=MyValue&M
yOtherVariable=MyOtherValue");
7
QueryStrings
• Read querystring values through
Request.QueryString
[c#]
MyValue =
Request.QueryString["MyVariable"];
[vb]
MyValue =
Request.QueryString("MyVariable“)
8
Server.Transfer and Context.Items
• Use to pass a variable from one to another without
changing the Page URL.
• In the first page, and the values you want to the
Content.Items collection:
[c#] Context.Items.Add("MyVariable”,MyValue);
[vb] Context.Items.Add("MyVariable”,MyValue)
• Then transfer to the second page:
[c#] Server.Transfer("SecondPage.aspx");
[vb] Server.Transfer("SecondPage.aspx")
9
Server.Transfer and Context.Items
• On the second page retrieve the value from the Context.Items
collection and cast to the type you need:
[c#] MyValue = (MyType)Context.Items["MyVariable"];
[vb] MyValue = Ctype(Context.Items("MyVariable“),MyType)
10
Cookies
• Cookies store data in the browser
• Either memory resident only (because no Expiry Date is given) and so only
available throughout a session.
• Or if an Expiry Date is given then Cookies will persist between sessions for a
user (with a consistent profile, login or machine)
[c#] HttpCookie ck = new HttpCookie("MyVariable",MyValue);
[vb] Dim ck as new HttpCookie("MyVariable",MyValue)
11
Cookies
• Create a cookie using HttpCookie and then add it to
Response.Cookies collection to send it to the browser.
[c#]
ck.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(ck);
[vb]
ck.Expires = DateTime.Now.AddDays(30)
Response.Cookies.Add(ck)
12
Cookies
• Read a cookie by retrieving it from the
Request.Cookies collection:
[c#]
HttpCookie ck;
ck = Request.Cookies["MyVariable"];
[vb]
Dim ck as HttpCookie
ck = Request.Cookies("MyVariable“)
13
Cookies
• Delete a cookie by setting it's expiry date to yesterday (or
earlier) and adding to the Response.Cookies collection
[c#]
ck.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(ck);
[vb]
ck.Expires = DateTime.Now.AddDays(-1)
Response.Cookies.Add(ck)
14
15
Application and Session Objects –
Reloaded.
• Application – contains a collection of data
that is available across the entire application
during the life of the application.
• Session – contains data that is available
across all pages accessed by a single user
during a single session.
• You can write code to respond to Application
and Session events in the global.asax file.
16
Session State
• Session state is maintained on a per-client basis.
• When a client first accesses any page in an
application, an ASP.NET generated session ID is
created.
• Session state is used for things like:
• Shopping carts, Viewing preferences, other
• Session state is the most flexible and, in general,
the most efficient means of maintaining client-
specific state.
17
Session Events
Event Description
Session_OnStart Occurs when a new user accesses a page
that’s part of the application. Can be used to
initialize: session variables, session level
objects, and begin database connections.
Session_OnEnd Happens when a session times out. Can be
used to any final cleanup and to close a
database connection.
18
Using the Session Object
• Session state is maintained on behalf of each client
within an ASP.NET application.
• When a new client begins to interact with the
application, a new session ID (or session key) is
generated
• The ID is associated with all subsequent requests from
that same client.
• The state is retained in memory on the server in the
default session state configuration.
• By default, the session key is retained on the client side
in a cookie. (there is an alternative in cases where
cookies do not work)
19
20
Session Variables
• Session variables store data for each user session and can
be used anywhere in the site.
[c#] Session.Add("MyVariable“,MyValue);
vb] Session.Add("MyVariable“,MyValue)
• By default they use a memory resident cookie to relate the
user to their set of variables.
• By default they are not very scalable since each user
consumes more memory
21
Session Variables
• Sessions timeout after a period of inactivity (default 20mins)
• Session Settings in Web.Config can make Session variables work
with query strings rather than cookies, change the timeout value,
and move state to another machine, or SQL server to improve
scalability.
• Global.asax has events for the Session that you can utilize (e.g.
Session_Start)
22
Configuring Session Mode
• InProc
• StateServer
• Database
23
Example
<sessionState mode="InProc"
cookieless="false" timeout="20" />
<sessionState mode="StateServer"
stateConnectionString="tcpip=myserver:42424"
cookieless="false" timeout="20" />
<sessionState mode="SqlServer"
sqlConnectionString="data
source=127.0.0.1;user id=sa; password="
cookieless="false" timeout="20" />
24
Application State
• Application state is where information that is global to
the application may be stored.
• For efficiency, this state is typically stored once and then
read from many times.
• Often used for application statistics variables or constant
global data:
• Number of users who have accessed site
• Counts of different types of browsers
• Can prefetch static data from a database or file
• Should be used with care
25
Application Events
Event Description
Application_OnStart Happens once – when the first user access the
app. Can be used to retrieve or initialize
information that will be used across all
sessions.
Application_OnEnd Happens once – when the last user leaves the
app. Can be used to clean up any app-level
variables and objects.
Application_OnBeginRequ Happens every time a page in the application
est is requested, before the request is serviced.
Application_OnEndReques Happens after each request is serviced. The
t last event that can have an effect on the
response.
26
Using the Application Object
• Application object is implicitly locked for you when data is read
from or written to it.
• May make more sense to avoid using application object and use
data cache if you are just storing global constants.
• Application object must be used if you are using shared,
updatable data.
27
Application Variables
• Application variables store data for the Application and can be
used anywhere in the site.
[c#] Application.Lock();
Application["MyVariable"] = MyValue;
Appliction.UnLock();
[vb] Application.Lock()
Application("MyVariable“) = MyValue
Appliction.UnLock()
28