© minder chen, 2001-2003 asp.net - 1 form handling and state maintenance major build-in asp.net...

44
© Minder Chen, 2001- ASP.NET - 1 Form 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)

Upload: spencer-day

Post on 20-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 1

Form 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)

Page 2: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 2

Major Build-in ASPX ObjectsC

l i e

n t

S e

r v

e r

Request Object• Cookies• Form• QueryString• ServerVariables• ClientCertificateResponse Object

• Cookies• (Properties)• (Methods)

Server Object• (Properties)• (Methods)

Application ObjectSession ObjectCache Object

Page 3: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 3

Form Data Handling Without PostBack

Page 4: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 4

Form Method=post

<html><body>

<form action="greeting.aspx" method="post">Enter your name:

<input type="text" name="guestName"> <br>

<input type="submit" value="Submit your name">

</form></body></html>

greeting.htm

<html><head><title>Greetings</title></head>

<body>

Hello <%= request.form("guestName") %> !

</body></html>

greeting.aspx

Page 5: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 5

Form Method=get

<html><body>

<form action="greeting2.aspx"

method="get">Enter your name:

<input type="text" name="guestName"> <br>

<input type="submit" value="Submit your name">

</form></body></html>

greeting2.htm

<html><head><title>Greetings</title></head>

<body>

Hello <%= request.QueryString("guestName") %> !

</body></html>

greeting2.aspx

Page 6: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 6

Query 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?category=basic&price=100

• 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."

QueryStringQueryString

Page 7: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 7

Multiple Values of a Variable

http://localhost/aspsimple/list.aspx?food=Melon&food=Water%20Melon&food=Pineapple

Page 8: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 8

List.aspx<HTML><script runat=server> private sub foodlist() Dim food As StringIf Request.Params.GetValues("food")Request.Params.GetValues("food") Is Nothing Is Nothing Then Response.Write("None of the foods have been chosen!" & "<BR>")Else

For Each food In For Each food In Request.Params.GetValues("food")Request.Params.GetValues("food") Response.Write(food & "<BR>")Response.Write(food & "<BR>") NextNextEnd IfEnd Sub</script> <body><% foodlist() %></body></HTML>

Page 9: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 9

foodform.aspx <html><head><title>Food</title></head><body><form method="GET" action="list.aspx"> <p><select size="3" name="food" multiple> <option>Apple</option> <option>Bread</option> <option>Pineapple</option> <option>Orange</option> <option>Rice</option> </select></p> <p><input type="submit" value="Submit"><input type="reset" value="Reset"></p></form>

<a href='computer.aspx?id=<%=Server.URLEncode("apple computer")%>'>

I like apple computer </a><br><a href="computer.aspx?id=Intel computer">I like Intel computer </a></body></html>

Page 10: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 10

computer.aspx<html><head><title> Computer </title></head>

<body><% = "The computer that you like: " & Request.querystring("ID") %>

</body></html>

Page 11: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 11

Request.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.

Page 12: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 12

Hypertext Links and Forms

• Hypertext link– <a href="URL?x=3&y=Hello">Next</a>

• Forms<form action="URL" method="post">

Form elements

</form>

• URL of the form handling page. • The default action is to submit to the form itself,

a common practice in ASP.NET.

Post: Send form data as standard input Get: Send form data as QueryString

QueryString

Page 13: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 13

Variable Name• Web forms submitting form data via PostBack use the form

elements idid 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' namename 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).

Page 14: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 14

State 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.

Page 15: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 15

Cookie

BrowserWorkstation

Web Server

Set cookie entries

Return cookie entries

Page 16: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 16

cookie.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/ FALSE 942189160 code 00L

iisa.microsoft.com FALSE /iis3 FALSE 946627200 NEWVISITOR N

.netscape.com TRUE / FALSE 946684799 NETSCAPE_ID000e010,100d11a9

ad.doubleclick.net FALSE / FALSE 942191940 IAF cb3254

www.allaire.com FALSE / FALSE 2137622400 CFID 10100

127.0.0.1 FALSE / FALSE 867761715 BCOLOR GREEN

Domain Set by client-side script

Expiration time: # of secondssince 1 Jan 1970

Secure?

Name Value

Page 17: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 17

State Management RecommendationsMethod Use when

View stateView state You need to store small amounts of information for a page that will post back to itself. Use of the ViewState property provides functionality with basic security.

Hidden fieldsHidden fields You need to store small amounts of information for a page via a form form that will post back to itself or another page, and when security is not an issue. Note:  You can use a hidden field only on pages that are submitted to the server.

CookiesCookies You need to store small amounts of information on the client when security is not a major issue. You can store persistent data via cookie.

Query stringQuery string You are transferring small amounts of information from one page to another via hypertext linkshypertext links and security is not an issue. Note: You can use query strings only if you are requesting the same page, or another page via a link.

ViewState: http://msdn.microsoft.com/msdnmag/issues/03/02/CuttingEdge/default.aspx

Page 18: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 18

ASP Application and Session Objects

I I S

ASP.NETApplicationObject 1

ApplicationObject 2

ApplicationObject 3

Session Object 3

Session Object 2

Session Object 1

Session Object 3

Session Object 2

Session Object 1

Session Object 3

Session Object 2

Session Object 1

Page 19: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 19

Application 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.

Page 20: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 20

ASP 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.

Page 21: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 21

Session Object and ViewState Object Session ("UserName") = "John" Session ("UserName") = "John" ' in page1' 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 StringS = 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"

Page 22: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 22

Store 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.asxIn page1.asx

Dim x1 as New ClassX()

Session("sv_x") = x1

In page2.aspxIn page2.aspx

Dim x2 as New ClassX()

x2 = CType(Session("sv_x"), ClassX)CType(Session("sv_x"), ClassX)

Page 23: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 23

Using 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.

Page 24: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 24

Session Variables

Logon.aspx

Session2.aspx

Page 25: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 25

Logon.aspx<%@ Page Language="vb" AutoEventWireup="false"

Codebehind="logon.aspx.vb" Inherits="exstate.Logon"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML> <HEAD><title>session1</title></HEAD> <body> <form id="Form1" method="post" runat="server"> <P>User name: <asp:TextBox id="TextBoxUserID" runat="server"></asp:TextBox></P> <P>Password: <asp:TextBox id="TextBoxPassword" runat="server" TextMode="Password">

</asp:TextBox></P> <P>First name: <asp:TextBox id="TextBoxFirst" runat="server"></asp:TextBox></P> <P>Last Name: <asp:TextBox id="TextBoxLast" runat="server"></asp:TextBox></P> <P><asp:Button id="Button1" runat="server" Text="Submit"></asp:Button></P> <P><asp:Label id="LabelMsg" runat="server"></asp:Label></P> </form> </body></HTML>

Page 26: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 26

Logon.aspx.vbPublic 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"Request.Params.Get("msg") = "userid" Then

LabelMsg.Text = "Please login before you visit other pages on this site."

End If

End If

End Sub

Page 27: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 27

Continued…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 <> "" 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 BooleanPrivate Function Check(ByVal user As String, ByVal pswd As String) As Boolean If user = pswd Then Return True Else Return False End If End FunctionEnd Class

Page 28: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 28

User Class

Public Class User

Public FirstName As String

Public LastName As String

End Class

Page 29: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 29

Sesison2.aspx<%@ Page Language="vb" AutoEventWireup="false"

Codebehind="Session2.aspx.vb" Inherits="exstate.Session2"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML> <HEAD> <title>Session2</title> </HEAD> <body> <form id="Form1" method="post" runat="server"> <P>Hi <asp:Label id="LabelFirstName" runat="server"></asp:Label> <asp:Label id="LabelLastName" runat="server">

</asp:Label></P> <P>Your User ID is: <asp:Label id="LabelUserID" runat="server"></asp:Label></P> </form> </body></HTML>

Page 30: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 30

Session2.aspx.vbPublic 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?msg=userid") Else CurrentUser = CType(Session("UserName"), User) LabelFirstName.Text = CurrentUser.FirstName LabelLastName.Text = CurrentUser.LastName End If End SubEnd Class

Page 31: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 31

Dynamic Web Site for EC

Source: Adapted from Technology Forecast 2000. PriceWaterhouseCoopers.

Session IDSession Variables

http://etail.com/shop.aspx?

<%= session("Name1") + session("Name2") %><% While (dr.Next()) %> <p><PROD> <%= dw.getString("Product") %> </PROD></P> <% End While %>

Page 32: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 32

WebForm1.aspx

End the session and then submit again!

Page 33: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 33

WebForm1.aspx<%@ Page Language="vb" AutoEventWireup="false"

Codebehind="WebForm1.aspx.vb" Inherits="state.WebForm1"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML> <HEAD> <title>WebForm1</title> <meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR"> <meta content="Visual Basic 7.0" name="CODE_LANGUAGE"> <meta content="JavaScript" name="vs_defaultClientScript"> <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema"> </HEAD> <body>

<form id="Form1" method="post" runat="server">

<P>ViewState: <asp:textbox id="TextBoxViewState" runat="server"></asp:textbox></P>

<P>Cookie: <asp:textbox id="TextBoxCookie" runat="server"></asp:textbox></P>

<P>Session: <asp:textbox id="TextBoxSession" runat="server"></asp:textbox></P>

<P>Application: <asp:textbox id="TextBoxApplication" runat="server">

</asp:textbox></P>

<P><asp:button id="ButtonSubmit" runat="server" Text="Submit!">

</asp:button>&nbsp;&nbsp;&nbsp;

<asp:button id="ButtonEndSession" runat="server" Text="End Session">

</asp:button>&nbsp;&nbsp;

<asp:button id="ButtonGoWebForm2" runat="server" Text="Go to WebForm2">

</asp:button></P>

<P><asp:label id="Label1" runat="server"></asp:label></P>

</form></body></HTML>

Page 34: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 34

WebForm1.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

Page 35: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 35

Continued…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 &= "<br>Cookie variable = Nothing" Else Label1.Text &= "<br>Cookie 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. Response.Cookies.Add(ck1) Else Label1.Text &= "<br>Your browser doesn't support cookie!" End If

Page 36: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 36

Continued…If Session.IsNewSession Then Label1.Text &= "<br>This is a new session!" End If If Session("sv1") Is Nothing Then Label1.Text &= "<br>Session variable = Nothing" Else Label1.Text &= "<br>Session variable = " & Session("sv1") Label1.Text &= "<br>Session ID = " & Session.SessionID.ToString() Label1.Text &= "<br>Session Timeout = " & Session.Timeout End If Session("sv1") = TextBoxSession.Text

If Application("av1") Is Nothing Then Label1.Text &= "<br>Application variable = Nothing" Else Label1.Text &= "<br>Application variable = " & Application("av1") End If Application("av1") = TextBoxApplication.Text End Sub

Page 37: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 37

Continued…

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

Page 38: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 38

Global.asaxImports System.WebImports System.Web.SessionStatePublic 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_StartSession_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() End Sub

Page 39: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 39

Continued… 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) ' Fires when the application ends End SubEnd Class

Page 40: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 40

The 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.

Page 41: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 41

Cookieless Session

<configuration>

<system.web>

<sessionState

mode="InProc"

stateConnectionString="tcpip=127.0.0.1:42424"

sqlConnectionString="data source=127.0.0.1;user id=sa;password="

cookieless="true"

timeout="20"

/>

</configuration>

</system.web>

Web.configWeb.config

Default value is false

• InProc• StateServer• SQLServer

• 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 <a href="/abc/page1.aspx">Test</a>

Page 42: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 42

Source:

http://www.fawcette.com/dotnetmag/2002_10/online/bolges/default_pf.asp

Page 43: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 43

Cookieless Session

Page 44: © Minder Chen, 2001-2003 ASP.NET - 1 Form Handling and State Maintenance Major Build-in ASP.NET Objects Simple Form Handling HTML Forms More Complex Form

© Minder Chen, 2001-2003 ASP.NET - 44

Variables ScopeTypeType RetrievalRetrieval CreationCreation ScopeScopeForm 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!