This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
• 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)
• 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."
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>
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).
• 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.
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.
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.
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.
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
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
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
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
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
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.