Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "© 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."— Presentation transcript:

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 Processing State Maintenance Overview ViewState and Cookies Variables Application and Session Variables Navigating Between Web Pages (Forms)

2 © Minder Chen, 2001-2003 ASP.NET - 2 Major Build-in ASPX Objects C l i e n t S e r v e r Request Object Cookies Form QueryString ServerVariables ClientCertificate Response Object Cookies (Properties) (Methods) Server Object (Properties) (Methods) Application Object Session Object Cache Object

3 © Minder Chen, 2001-2003 ASP.NET - 3 Form Data Handling Without PostBack

4 © Minder Chen, 2001-2003 ASP.NET - 4 Form Method=post Enter your name: greeting.htm Greetings Hello ! greeting.aspx

5 © Minder Chen, 2001-2003 ASP.NET - 5 Form Method=get <form action="greeting2.aspx" method="get"> Enter your name: greeting2.htm Greetings Hello ! greeting2.aspx

6 © 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." QueryString

7 © Minder Chen, 2001-2003 ASP.NET - 7 Multiple Values of a Variable http://localhost/aspsimple/list.aspx?food=Melon&food=Water%20Melon&food=Pineapple

8 © Minder Chen, 2001-2003 ASP.NET - 8 List.aspx private sub foodlist() Dim food As String Request.Params.GetValues("food") Is Nothing If Request.Params.GetValues("food") Is Nothing Then Response.Write("None of the foods have been chosen!" & " ") Else For Each food In Request.Params.GetValues("food") For Each food In Request.Params.GetValues("food") Response.Write(food & " ") Response.Write(food & " ") Next Next End If End Sub

9 © Minder Chen, 2001-2003 ASP.NET - 9 foodform.aspx Food Apple Bread Pineapple Orange Rice '> I like apple computer I like Intel computer

10 © Minder Chen, 2001-2003 ASP.NET - 10 computer.aspx Computer

11 © Minder Chen, 2001-2003 ASP.NET - 11 Request.Params Gets a combined collection of QueryString, Form, ServerVariables, and Cookies items. QueryStringFormServerVariablesCookies Request.Params.Get("name") –Gets the values of a specified entry in the NameValueCollection combined into one comma- separated list.NameValueCollection –A String is return. Request.Params.GetValues("name") –Gets the values of a specified entry in the NameValueCollection.NameValueCollection – An array of String is returned.

12 © Minder Chen, 2001-2003 ASP.NET - 12 Hypertext Links and Forms Hypertext link – Next Forms Form elements 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

13 © Minder Chen, 2001-2003 ASP.NET - 13 Variable Name idWeb 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 nameWeb 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).NameValueCollection

14 © 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.

15 © Minder Chen, 2001-2003 ASP.NET - 15 Cookie Browser Workstation Web Server Set cookie entries Return cookie entries

16 © 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/FALSE942189160code00L iisa.microsoft.comFALSE/iis3FALSE946627200NEWVISITORN.netscape.comTRUE/FALSE946684799NETSCAPE_ID000e010,100d11a9 ad.doubleclick.netFALSE/FALSE942191940IAFcb3254 www.allaire.comFALSE/FALSE2137622400CFID10100 127.0.0.1FALSE/FALSE867761715BCOLORGREEN DomainSet by client-side script Expiration time: # of seconds since 1 Jan 1970 Secure? Name Value

17 © Minder Chen, 2001-2003 ASP.NET - 17 State Management Recommendations MethodUse when View 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 fields form You need to store small amounts of information for a page via a 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. Cookies 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 string hypertext links You are transferring small amounts of information from one page to another via hypertext 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

18 © Minder Chen, 2001-2003 ASP.NET - 18 ASP Application and Session Objects I I S ASP.NET Application Object 1 Application Object 2 Application Object 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

19 © 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.

20 © 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.

21 © Minder Chen, 2001-2003 ASP.NET - 21 Session 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"

22 © 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.asx Dim x1 as New ClassX() … Session("sv_x") = x1 In page2.aspx Dim x2 as New ClassX() CType(Session("sv_x"), ClassX) x2 = CType(Session("sv_x"), ClassX)

23 © 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.

24 © Minder Chen, 2001-2003 ASP.NET - 24 Session Variables Logon.aspx Session2.aspx

25 © Minder Chen, 2001-2003 ASP.NET - 25 Logon.aspx <%@ Page Language="vb" AutoEventWireup="false" Codebehind="logon.aspx.vb" Inherits="exstate.Logon"%> session1 User name: Password: First name: Last Name:

26 © Minder Chen, 2001-2003 ASP.NET - 26 Logon.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 Request.Params.Get("msg") = "userid" If Request.Params.Get("msg") = "userid" Then LabelMsg.Text = "Please login before you visit other pages on this site." End If End Sub

27 © 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 Boolean If user = pswd Then Return True Else Return False End If End Function End Class

28 © Minder Chen, 2001-2003 ASP.NET - 28 User Class Public Class User Public FirstName As String Public LastName As String End Class

29 © Minder Chen, 2001-2003 ASP.NET - 29 Sesison2.aspx <%@ Page Language="vb" AutoEventWireup="false" Codebehind="Session2.aspx.vb" Inherits="exstate.Session2"%> Session2 Hi Your User ID is:

30 © Minder Chen, 2001-2003 ASP.NET - 30 Session2.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?msg=userid") Else CurrentUser = CType(Session("UserName"), User) LabelFirstName.Text = CurrentUser.FirstName LabelLastName.Text = CurrentUser.LastName End If End Sub End Class

31 © Minder Chen, 2001-2003 ASP.NET - 31 Dynamic Web Site for EC Source: Adapted from Technology Forecast 2000. PriceWaterhouseCoopers. Session ID Session Variables http://etail.com/shop.aspxhttp://etail.com/shop.aspx?

32 © Minder Chen, 2001-2003 ASP.NET - 32 WebForm1.aspx End the session and then submit again!

33 © Minder Chen, 2001-2003 ASP.NET - 33 WebForm1.aspx <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="state.WebForm1"%> WebForm1 ViewState: Cookie: Session: Application:

34 © 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

35 © 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 &= " Cookie variable = Nothing" Else Label1.Text &= " 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 &= " Your browser doesn't support cookie!" End If

36 © Minder Chen, 2001-2003 ASP.NET - 36 Continued… If Session.IsNewSession Then Label1.Text &= " This is a new session!" End If If Session("sv1") Is Nothing Then Label1.Text &= " Session variable = Nothing" Else Label1.Text &= " Session variable = " & Session("sv1") Label1.Text &= " Session ID = " & Session.SessionID.ToString() Label1.Text &= " Session Timeout = " & Session.Timeout End If Session("sv1") = TextBoxSession.Text If Application("av1") Is Nothing Then Label1.Text &= " Application variable = Nothing" Else Label1.Text &= " Application variable = " & Application("av1") End If Application("av1") = TextBoxApplication.Text End Sub

37 © 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

38 © Minder Chen, 2001-2003 ASP.NET - 38 Global.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 Session_Start 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() End Sub

39 © 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 Sub End Class

40 © 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.

41 © Minder Chen, 2001-2003 ASP.NET - 41 Cookieless Session <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" /> Web.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 Test

42 © Minder Chen, 2001-2003 ASP.NET - 42 Source: http://www.fawcette.com/do tnetmag/2002_10/online/ bolges/default_pf.asp

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

44 © Minder Chen, 2001-2003 ASP.NET - 44 Variables ScopeTypeRetrievalCreationScope 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") = 1Same page during PostBack Session Session("x") Session("x") = 1Same visitor during a session Application Application("x") Application("x") = 1All pages from the same site!


Download ppt "© 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."

Similar presentations


Ads by Google