440 likes | 600 Views
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).
E N D
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)
Major 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
Form Method=post greeting.htm <html><body> <formaction="greeting.aspx"method="post"> Enter your name: <inputtype="text"name="guestName"> <br> <inputtype="submit"value="Submit your name"> </form></body></html> greeting.aspx <html><head><title>Greetings</title></head> <body> Hello <%= request.form("guestName") %> ! </body></html>
Form Method=get greeting2.htm <html><body> <formaction="greeting2.aspx" method="get"> Enter your name: <inputtype="text"name="guestName"> <br> <inputtype="submit"value="Submit your name"> </form></body></html> greeting2.aspx <html><head><title>Greetings</title></head> <body> Hello <%= request.QueryString("guestName") %> ! </body></html>
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
Multiple Values of a Variable http://localhost/aspsimple/list.aspx?food=Melon&food=Water%20Melon&food=Pineapple
List.aspx <HTML> <scriptrunat=server> private sub foodlist() Dim food As String If Request.Params.GetValues("food") Is Nothing Then Response.Write("None of the foods have been chosen!" & "<BR>") Else For Each food In Request.Params.GetValues("food") Response.Write(food & "<BR>") Next End If End Sub </script> <body> <% foodlist() %> </body> </HTML>
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>
computer.aspx <html><head><title> Computer </title></head> <body> <% = "The computer that you like: " & Request.querystring("ID") %> </body></html>
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.
Hypertext Links and Forms • Hypertext link • <a href="URL?x=3&y=Hello">Next</a> • Forms <form action="URL" method="post"> Form elements </form> 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.
Variable 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).
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.
Cookie Set cookie entries Web Server Browser Workstation Return cookie entries
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_ID 000e010,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 Name Value Expiration time: # of seconds since 1 Jan 1970 Secure? Domain Set by client-side script
Method Use when State Management Recommendations 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 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 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
ASP 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
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.
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.
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"
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() x2 = CType(Session("sv_x"), ClassX)
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.
Session Variables Logon.aspx Session2.aspx
Logon.aspx <%@ Page Language="vb" AutoEventWireup="false" Codebehind="logon.aspx.vb" Inherits="exstate.Logon"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><title>session1</title></HEAD> <body> <formid="Form1"method="post"runat="server"> <P>User name: <asp:TextBoxid="TextBoxUserID"runat="server"></asp:TextBox></P> <P>Password: <asp:TextBoxid="TextBoxPassword"runat="server"TextMode="Password"> </asp:TextBox></P> <P>First name: <asp:TextBoxid="TextBoxFirst"runat="server"></asp:TextBox></P> <P>Last Name: <asp:TextBoxid="TextBoxLast"runat="server"></asp:TextBox></P> <P><asp:Buttonid="Button1"runat="server"Text="Submit"></asp:Button></P> <P><asp:Labelid="LabelMsg"runat="server"></asp:Label></P> </form> </body> </HTML>
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 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
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
User Class Public Class User Public FirstName As String Public LastName As String End Class
Sesison2.aspx <%@ Page Language="vb" AutoEventWireup="false" Codebehind="Session2.aspx.vb" Inherits="exstate.Session2"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>Session2</title> </HEAD> <body> <formid="Form1"method="post"runat="server"> <P>Hi <asp:Labelid="LabelFirstName"runat="server"></asp:Label> <asp:Labelid="LabelLastName"runat="server"> </asp:Label></P> <P>Your User ID is: <asp:Labelid="LabelUserID"runat="server"></asp:Label></P> </form> </body> </HTML>
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 SubPage_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
Dynamic Web Site for EC Session ID Session Variables http://etail.com/shop.aspx? <%= session("Name1") + session("Name2") %> <% While (dr.Next()) %> <p><PROD> <%= dw.getString("Product") %> </PROD></P> <% End While %> Source: Adapted from Technology Forecast 2000. PriceWaterhouseCoopers.
WebForm1.aspx End the session and then submit again!
WebForm1.aspx <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="state.WebForm1"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>WebForm1</title> <metacontent="Microsoft Visual Studio.NET 7.0"name="GENERATOR"> <metacontent="Visual Basic 7.0"name="CODE_LANGUAGE"> <metacontent="JavaScript"name="vs_defaultClientScript"> <metacontent="http://schemas.microsoft.com/intellisense/ie5"name="vs_targetSchema"> </HEAD> <body> <formid="Form1"method="post"runat="server"> <P>ViewState: <asp:textboxid="TextBoxViewState"runat="server"></asp:textbox></P> <P>Cookie: <asp:textboxid="TextBoxCookie"runat="server"></asp:textbox></P> <P>Session: <asp:textboxid="TextBoxSession"runat="server"></asp:textbox></P> <P>Application: <asp:textboxid="TextBoxApplication"runat="server"> </asp:textbox></P> <P><asp:buttonid="ButtonSubmit"runat="server"Text="Submit!"> </asp:button> <asp:buttonid="ButtonEndSession"runat="server"Text="End Session"> </asp:button> <asp:buttonid="ButtonGoWebForm2"runat="server"Text="Go to WebForm2"> </asp:button></P> <P><asp:labelid="Label1"runat="server"></asp:label></P> </form></body></HTML>
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
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
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
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
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 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
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
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.
Cookieless Session Web.config <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> • InProc • StateServer • SQLServer 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 <a href="/abc/page1.aspx">Test</a>
Source: http://www.fawcette.com/dotnetmag/2002_10/online/bolges/default_pf.asp