Title: Form Handling and State Maintenance
1Form Handling and State Maintenance
- Major Build-in ASP.NET Objects
- Simple Form Handling
- HTML Forms
- More Complex Form Processing
- State Maintenance Overview
- ViewState and Cookies Variables
- Application and Session Variables
- Navigating Between Web Pages (Forms)
2Major Build-in ASPX Objects
- Request Object
- Cookies
- Form
- QueryString
- ServerVariables
- ClientCertificate
- Response Object
- Cookies
- (Properties)
- (Methods)
S e r v e r
C l i e n t
- Server Object
- (Properties)
- (Methods)
Application Object Session Object Cache Object
3Form Data Handling Without PostBack
4Form Methodpost
greeting.htm
- lthtmlgtltbodygt
- ltform action"greeting.aspx" method"post"gt
- Enter your name
- ltinput type"text" name"guestName"gt ltbrgt
- ltinput type"submit" value"Submit your name"gt
- lt/formgtlt/bodygtlt/htmlgt
greeting.aspx
lthtmlgtltheadgtlttitlegtGreetingslt/titlegtlt/headgt ltbodygt
Hello lt request.form("guestName") gt
! lt/bodygtlt/htmlgt
5Form Methodget
greeting2.htm
lthtmlgtltbodygt ltform action"greeting2.aspx"
method"get"gt Enter your name ltinput
type"text" name"guestName"gt ltbrgt ltinput
type"submit" value"Submit your
name"gt lt/formgtlt/bodygtlt/htmlgt
greeting2.aspx
lthtmlgtltheadgtlttitlegtGreetingslt/titlegtlt/headgt ltbodygt
Hello lt request.QueryString("guestName") gt
! lt/bodygtlt/htmlgt
6Query Strings
- A query string is information appended to the end
of a page's URL. A typical example might look
like the following - http//localhost/test.aspx?categorybasicprice10
0 - In the URL path above, the query string starts
with the question mark (?) and includes two
name-value pairs, one called "category" and the
other called "price."
QueryString
7Multiple Values of a Variable
http//localhost/aspsimple/list.aspx?foodMelonfo
odWater20MelonfoodPineapple
8List.aspx
- ltHTMLgt
- ltscript runatservergt
- private sub foodlist()
- Dim food As String
- If Request.Params.GetValues("food") Is Nothing
Then - Response.Write("None of the foods have been
chosen!" "ltBRgt") - Else
- For Each food In Request.Params.GetValues("foo
d") - Response.Write(food "ltBRgt")
- Next
- End If
- End Sub
- lt/scriptgt
- ltbodygt
- lt foodlist() gt
- lt/bodygt
- lt/HTMLgt
9foodform.aspx
- lthtmlgtltheadgtlttitlegtFoodlt/titlegtlt/headgt
- ltbodygt
- ltform method"GET" action"list.aspx"gt
- ltpgtltselect size"3" name"food" multiplegt
- ltoptiongtApplelt/optiongt
- ltoptiongtBreadlt/optiongt
- ltoptiongtPineapplelt/optiongt
- ltoptiongtOrangelt/optiongt
- ltoptiongtRicelt/optiongt
- lt/selectgtlt/pgt
- ltpgt
- ltinput type"submit" value"Submit"gt
- ltinput type"reset" value"Reset"gtlt/pgt
- lt/formgt
- lta href'computer.aspx?idltServer.URLEncode("app
le computer")gt'gt - I like apple computer lt/agtltbrgt
- lta href"computer.aspx?idIntel computer"gtI like
Intel computer lt/agt - lt/bodygtlt/htmlgt
10computer.aspx
- lthtmlgtltheadgtlttitlegt Computer lt/titlegtlt/headgt
- ltbodygt
- lt "The computer that you like "
Request.querystring("ID") gt - lt/bodygtlt/htmlgt
11Request.Params
- Gets a combined collection of QueryString, Form,
ServerVariables, and Cookies items. - Request.Params.Get("name")
- Gets the values of a specified entry in the
NameValueCollection combined into one
comma-separated list. - A String is return.
- Request.Params.GetValues("name")
- Gets the values of a specified entry in the
NameValueCollection. - An array of String is returned.
12Hypertext Links and Forms
- Hypertext link
- lta href"URL?x3yHello"gtNextlt/agt
- Forms
- ltform action"URL" method"post"gt
- Form elements
- lt/formgt
QueryString
Post Send form data as standard input Get Send
form data as QueryString
- URL of the form handling page.
- The default action is to submit to the form
itself, a common practice in ASP.NET.
13Variable Name
- Web forms submitting form data via PostBack use
the form elements id attribute's values as
identifiers - You have to use HTML Server Controls or Web
Server Controls - E.g., Text1.Text
- Web forms submitting to another ASPX page where
form elements' name attribute's values are used
as identifiers. - Post method Request.Form("x")
- Get method Request.QueryString("x")
- Both Post and Get
- Single value
- Request.Params.Get("x") return a string
- Multiple values
- Request.Params.GetValues("x") return an array
of strings - Request.Params.Get("x") Get the values of a
specified entry in the NameValueCollection
combined into one comma-separated list (string).
14State Maintenance
- Web (HTTP) uses a stateless protocol.
- Web forms are created and destroyed each time a
client browser makes a request. - Because of this characteristic, variables
declared within a Web form do not retain their
value after a page is displayed. - ASP.NET provides different mechanisms to retain
data on a Web form between requests. - To solve this problem, ASP.NET provides several
ways to retain variables' values between requests
depending on the nature and scope of the
information.
15Cookie
Set cookie entries
Web Server
Browser Workstation
Return cookie entries
16cookie.txt at Your Browser'S Root Directory
- Netscape HTTP Cookie File
- http//www.netscape.com/newsref/std/cookie_spec.
html - This is a generated file! Do not edit.
- 207.67.128.9 FALSE /cgi-bin/ads/ FALS
E 942189160 code 00L - iisa.microsoft.com FALSE /iis3 FALSE 946627200 NEW
VISITOR N - .netscape.com TRUE / FALSE 946684799 NETSCAPE_ID 0
00e010,100d11a9 - ad.doubleclick.net FALSE / FALSE 942191940 IAF cb3
254 - www.allaire.com FALSE / FALSE 2137622400 CFID 1010
0 - 127.0.0.1 FALSE / FALSE 867761715 BCOLOR GREEN
Name Value
Expiration time of seconds since 1 Jan 1970
Domain Set by client-side script
Secure?
17State Management Recommendations
ViewState http//msdn.microsoft.com/msdnmag/issue
s/03/02/CuttingEdge/default.aspx
18ASP Application and Session Objects
I I S
ASP.NET
Application Object 1
Application Object 2
Application Object 3
Session Object 1
Session Object 1
Session Object 1
Session Object 2
Session Object 2
Session Object 2
Session Object 3
Session Object 3
Session Object 3
19Application Object
- Global.asax is the ASPX file for each application
resides in the root directory of the application.
An ASP.NET application is the sum of all files,
pages, handlers, modules, and code that reside in
a given virtual directory and its subdirectories
and that users can request through that virtual
directory hierarchy.
20ASP and Session Management
- Hypertext Transfer Protocol (HTTP) is a stateless
protocol. Each browser request to a Web server is
independent, and the server retains no memory of
a browser's past requests. - The Session object, one of the intrinsic objects
supported by ASPX, provides a developer with a
complete Web session management solution. - The Session object supports a dynamic associative
array that a script can use to store information.
Scalar variables and object references can be
stored in the session object. - For each ASPX page requested by a user, the
Session object will preserve the information
stored for the user's session. This session
information is stored in memory on the server.
The user is provided with a unique session ID
that ASPX uses to match user requests with the
information specific to that user's session.
A session is terminated when you close the
browser.
21Session Object and ViewState Object
- Session ("UserName") "John" ' in page1
-
- Response.Write(Session("UserName")) ' in page2
- This will store the string "John" in the Session
object and give it the name "UserName." - This value can be retrieved from the Session
object by referencing the Session object by name,
as in the following -
- ViewState("t1") "Test"
- Dim s as String
- S ViewState("t1") ' ViewState("T1") is a
different variable! - You can only store a string in a cookie and in a
ViewState variable. - The ViewState variable names are case sensitive.
-
-
- See Online Help on "Saving Web Forms Page Values
Using View State"
22Store Objects as Session Variables in the Session
Object
- You may want to use CType() function to cast
session variable back to an appropriate object
before you use it. - In page1.asx
- Dim x1 as New ClassX()
-
- Session("sv_x") x1
- In page2.aspx
- Dim x2 as New ClassX()
- x2 CType(Session("sv_x"), ClassX)
23Using Session Objects
- You can use the Session object to store
information needed for a particular user-session.
- Variables stored in the Session object are not
discarded when the user jumps between pages in
the application instead, these variables persist
for the entire user-session. - The Web server automatically creates a Session
object when a Web page from the application is
requested by a user who does not already have a
session. - The server destroys the Session object when the
session expires or is abandoned. - One common use for the Session object is to store
user preferences.
24Session Variables
Session2.aspx
25Logon.aspx
- lt_at_ Page Language"vb" AutoEventWireup"false"
- Codebehind"logon.aspx.vb" Inherits"exstate.Log
on"gt - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - ltHTMLgt
- ltHEADgtlttitlegtsession1lt/titlegtlt/HEADgt
- ltbodygt
- ltform id"Form1" method"post"
runat"server"gt - ltPgtUser name
- ltaspTextBox id"TextBoxUserID"
runat"server"gtlt/aspTextBoxgtlt/Pgt - ltPgtPassword
- ltaspTextBox id"TextBoxPassword"
runat"server" TextMode"Password"gt
lt/aspTextBoxgtlt/Pgt - ltPgtFirst name
- ltaspTextBox id"TextBoxFirst"
runat"server"gtlt/aspTextBoxgtlt/Pgt - ltPgtLast Name
- ltaspTextBox id"TextBoxLast"
runat"server"gtlt/aspTextBoxgtlt/Pgt - ltPgtltaspButton id"Button1"
runat"server" Text"Submit"gtlt/aspButtongtlt/Pgt - ltPgtltaspLabel id"LabelMsg"
runat"server"gtlt/aspLabelgtlt/Pgt - lt/formgt
- lt/bodygt
26Logon.aspx.vb
- Public Class Logon
- Inherits System.Web.UI.Page
- Protected WithEvents TextBoxUserID As
System.Web.UI.WebControls.TextBox - Protected WithEvents TextBoxFirst As
System.Web.UI.WebControls.TextBox - Protected WithEvents TextBoxLast As
System.Web.UI.WebControls.TextBox - Protected WithEvents Button1 As
System.Web.UI.WebControls.Button - Protected WithEvents LabelMsg As
System.Web.UI.WebControls.Label - Protected WithEvents TextBoxPassword As
System.Web.UI.WebControls.TextBox - Region " Web Form Designer Generated Code "
- '
- End Region
- Private Sub Page_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load - LabelMsg.Text "" ' Reset Message
- If Not IsPostBack Then
- If Request.Params.Get("msg")
"userid" Then - LabelMsg.Text "Please login
before you visit other pages on this site." - End If
- End If
- End Sub
27Continued
- Private Sub Button1_Click (ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles Button1.Click - Dim NewUser As New User()
- If TextBoxUserID.Text ltgt "" Then
- If Check(TextBoxUserID.Text,
TextBoxPassword.Text) Then - Session("UserID")
TextBoxUserID.Text - NewUser.FirstName
TextBoxFirst.Text - NewUser.LastName
TextBoxLast.Text - Session("UserName") NewUser
- Response.Redirect("session2.aspx")
- Else
- LabelMsg.Text "Your user id and
password does not match what is in our file" - End If
- Else
- LabelMsg.Text "You need to enter
your user id" - End If
- End Sub
- Private Function Check(ByVal user As String,
ByVal pswd As String) As Boolean - If user pswd Then
28User Class
- Public Class User
- Public FirstName As String
- Public LastName As String
- End Class
29Sesison2.aspx
- lt_at_ Page Language"vb" AutoEventWireup"false"
- Codebehind"Session2.aspx.vb" Inherits"exstate.S
ession2"gt - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - ltHTMLgt
- ltHEADgt
- lttitlegtSession2lt/titlegt
- lt/HEADgt
- ltbodygt
- ltform id"Form1" method"post"
runat"server"gt - ltPgtHi
- ltaspLabel id"LabelFirstName"
runat"server"gtlt/aspLabelgt - ltaspLabel id"LabelLastName"
runat"server"gt lt/aspLabelgtlt/Pgt - ltPgtYour User ID is
- ltaspLabel id"LabelUserID"
runat"server"gtlt/aspLabelgtlt/Pgt - lt/formgt
- lt/bodygt
- lt/HTMLgt
30Session2.aspx.vb
- Public Class Session2
- Inherits System.Web.UI.Page
- Protected WithEvents LabelFirstName As
System.Web.UI.WebControls.Label - Protected WithEvents LabelLastName As
System.Web.UI.WebControls.Label - Protected WithEvents LabelUserID As
System.Web.UI.WebControls.Label - Region " Web Form Designer Generated Code "
- ' ..
- End Region
- Private Sub Page_Load (ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load - LabelUserID.Text Session("UserID")
- Dim CurrentUser As New User()
- If Session("UserName") Is Nothing Then
- Response.Redirect("Logon.aspx?msguser
id") - Else
- CurrentUser CType(Session("UserName"
), User) - LabelFirstName.Text
CurrentUser.FirstName - LabelLastName.Text
CurrentUser.LastName - End If
- End Sub
31Dynamic Web Site for EC
Session ID
Session Variables
http//etail.com/shop.aspx?
lt session("Name1") session("Name2") gt lt
While (dr.Next()) gt ltpgtltPRODgt lt
dw.getString("Product") gt lt/PRODgtlt/Pgt
lt End While gt
Source Adapted from Technology Forecast 2000.
PriceWaterhouseCoopers.
32WebForm1.aspx
End the session and then submit again!
33WebForm1.aspx
- lt_at_ Page Language"vb" AutoEventWireup"false"
- Codebehind"WebForm1.aspx.vb"
Inherits"state.WebForm1"gt - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - ltHTMLgt
- ltHEADgt
- lttitlegtWebForm1lt/titlegt
- ltmeta content"Microsoft Visual
Studio.NET 7.0" name"GENERATOR"gt - ltmeta content"Visual Basic 7.0"
name"CODE_LANGUAGE"gt - ltmeta content"JavaScript"
name"vs_defaultClientScript"gt - ltmeta content"http//schemas.microsoft.co
m/intellisense/ie5" name"vs_targetSchema"gt - lt/HEADgt
- ltbodygt
- ltform id"Form1" method"post" runat"server"gt
- ltPgtViewState ltasptextbox
id"TextBoxViewState" runat"server"gtlt/asptextbox
gtlt/Pgt - ltPgtCookie ltasptextbox id"TextBoxCookie"
runat"server"gtlt/asptextboxgtlt/Pgt - ltPgtSession ltasptextbox id"TextBoxSession"
runat"server"gtlt/asptextboxgtlt/Pgt - ltPgtApplication ltasptextbox
id"TextBoxApplication" runat"server"gt - lt/asptextboxgtlt/Pgt
- ltPgtltaspbutton id"ButtonSubmit"
runat"server" Text"Submit!"gt
34WebForm1.aspx.vb
- Public Class WebForm1
- Inherits System.Web.UI.Page
- Protected WithEvents TextBoxViewState As
System.Web.UI.WebControls.TextBox - Protected WithEvents TextBoxCookie As
System.Web.UI.WebControls.TextBox - Protected WithEvents TextBoxSession As
System.Web.UI.WebControls.TextBox - Protected WithEvents TextBoxApplication As
System.Web.UI.WebControls.TextBox - Protected WithEvents ButtonSubmit As
System.Web.UI.WebControls.Button - Protected WithEvents ButtonEndSession As
System.Web.UI.WebControls.Button - Protected WithEvents ButtonGoWebForm2 As
System.Web.UI.WebControls.Button - Protected WithEvents Label1 As
System.Web.UI.WebControls.Label
35Continued
- Private Sub ButtonSubmit_Click(ByVal sender As
System.Object, - ByVal e As System.EventArgs) Handles
ButtonSubmit.Click - If ViewState("vs1") Is Nothing Then '
Check existence - Label1.Text "ViewState variable
Nothing" - Else
- Label1.Text "ViewState variable "
ViewState("vs1") - End If
- ViewState("vs1") TextBoxViewState.Text
- If Request.Browser.Cookies Then '
Browser support cookie - If Request.Cookies("cookie1") Is
Nothing Then - Label1.Text "ltbrgtCookie
variable Nothing" - Else
- Label1.Text "ltbrgtCookie
variable " Request.Cookies("cookie1").Value - End If
- ' Create a cookie.
- Dim ck1 As New HttpCookie("cookie1")
- ck1.Value TextBoxCookie.Text
- ck1.Expires Now.AddDays(1)
- ' Add the cookie.
36Continued
- If Session.IsNewSession Then
- Label1.Text "ltbrgtThis is a new
session!" - End If
- If Session("sv1") Is Nothing Then
- Label1.Text "ltbrgtSession variable
Nothing" - Else
- Label1.Text "ltbrgtSession variable
" Session("sv1") - Label1.Text "ltbrgtSession ID "
Session.SessionID.ToString() - Label1.Text "ltbrgtSession Timeout
" Session.Timeout - End If
- Session("sv1") TextBoxSession.Text
- If Application("av1") Is Nothing Then
- Label1.Text "ltbrgtApplication
variable Nothing" - Else
- Label1.Text "ltbrgtApplication
variable " Application("av1") - End If
- Application("av1") TextBoxApplication.Te
xt -
37Continued
- Private Sub ButtonEndSession_Click(ByVal sender
As System.Object, - ByVal e As System.EventArgs) Handles
ButtonEndSession.Click - Session.Abandon()
- ' Session.RemoveAll()
- End Sub
- Private Sub ButtonGoWebForm2_Click(ByVal sender
As System.Object, - ByVal e As System.EventArgs) Handles
ButtonGoWebForm2.Click - Dim x1 As New ClassX()
- Session("sv_x1") x1
- Response.Redirect("WebForm2.aspx")
- End Sub
- End Class
38Global.asax
- Imports System.Web
- Imports System.Web.SessionState
- Public Class Global
- Inherits System.Web.HttpApplication
- Region " Component Designer Generated Code "
- ..
- End Region
- Sub Application_Start(ByVal sender As Object,
ByVal e As EventArgs) - ' Fires when the application is started
- End Sub
- Sub Session_Start(ByVal sender As Object,
ByVal e As EventArgs) - ' Fires when the session is started
- ' Response.Redirect("Login.aspx")
- Application.Lock()
- If Application("ConurrentSession") Is
Nothing Then - Application("ConurrentSession") 0
- End If
- Application("ConurrentSession") 1
- Application.UnLock()
39Continued
- Sub Application_BeginRequest(ByVal sender As
Object, ByVal e As EventArgs) - ' Fires at the beginning of each request
- End Sub
- Sub Application_AuthenticateRequest(ByVal
sender As Object, ByVal e As EventArgs) - ' Fires upon attempting to authenticate
the use - End Sub
- Sub Application_Error(ByVal sender As Object,
ByVal e As EventArgs) - ' Fires when an error occurs
- End Sub
- Sub Session_End(ByVal sender As Object, ByVal
e As EventArgs) - ' Fires when the session ends
- Application.Lock()
- If Application("ConurrentSession") Is
Nothing Then - Application("ConurrentSession") 0
- End If
- Application("ConurrentSession") - 1
- Application.UnLock()
- End Sub
- Sub Application_End(ByVal sender As Object,
ByVal e As EventArgs)
40The Disadvantages of Using Cookies
- Limited size. Most browsers place a 4096-byte
limit on the size of a cookie, although the
support for 8192-byte cookie size is becoming
common in the new browser and client-device
versions available today. - User-configured refusal. Some users disable their
browser or client device's ability to receive
cookies, thereby limiting this functionality. - Security. Cookies are subject to tampering. Users
can manipulate cookies on their computer, which
can potentially represent a security compromise
or cause the application dependent on the cookie
to fail. - Durability. The durability of the cookie on a
client computer is subject to cookie expiration
processes on the client and user intervention. - Cookies are often used for personalization, where
content is customized for a known user. In most
of these cases, identification is the issue
rather than authentication, so it is enough to
merely store the user name, account name, or a
unique user ID (such as a GUID) in a cookie and
use it to access the user personalization profile
from a database of the site.
41Cookieless Session
Web.config
- InProc
- StateServer
- SQLServer
- ltconfigurationgt
- ltsystem.webgt
- ltsessionState
- mode"InProc"
- stateConnectionString"tcpip127.0.0.142424
" - sqlConnectionString"data
source127.0.0.1user idsapassword" - cookieless"true"
- timeout"20"
- /gt
- lt/configurationgt
- lt/system.webgt
Default value is false
- All the URL to pages in the web site must use
document relative URLs. - You cannot use absolute URLs or root relative
URLs, - such as lta href"/abc/page1.aspx"gtTestlt/agt
42- Source
- http//www.fawcette.com/dotnetmag/2002_10/online/b
olges/default_pf.asp
43Cookieless Session
44Variables Scope
Type Retrieval Creation Scope
Form Request.Form Request.Params.Get Request.Params.GetValues Form Post Method or PostBack HTML form elements Web Server Controls HTML Server Controls Current form via Postback Action page
URL Request.QueryString Request.Params.Get Request.Params.GetValues Query string of URL Form elements (Get Method) Hyperlinked or targeted page
Cookie Request.Cookies("x") Dim ck1 As New HttpCookie("x") ck1.Value TextBoxCookie.Text ck1.Expires Now.AddDays(1) Response.Cookies.Add(ck1) Before cookie expired from the same client station
ViewState Viewstate("x") ViewState("x") 1 Same page during PostBack
Session Session("x") Session("x") 1 Same visitor during a session
Application Application("x") Application("x") 1 All pages from the same site!