300 likes | 436 Views
Form Handling and State Maintenance. Major Build-in ASP.NET Objects State Maintenance Overview ViewState and Cookies Variables Application and Session Variables Optional Simple Form Handling HTML Forms More Complex Form Processing Navigating Between Web Pages (Forms).
E N D
Form Handling and State Maintenance • Major Build-in ASP.NET Objects • State Maintenance Overview • ViewState and Cookies Variables • Application and Session Variables • Optional • Simple Form Handling • HTML Forms • More Complex Form Processing • 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
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.
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>
Profile.htm: QueryString Collection • The QueryString collection retrieves form values passed to your Web server using HTTP GET method or retrieves variable-value pairs set as text followed a question mark in the request URL. <html> <body> <FORMMETHOD="GET"ACTION="profile.aspx"> First Name: <INPUTTYPE="text"NAME="firstname"><br> Last Name: <INPUTTYPE="text"NAME="lastname"><br> Age: <INPUTTYPE="text"NAME="age"><br> <INPUTTYPE="hidden"NAME="userstatus"VALUE="new"> <INPUTTYPE="submit"VALUE="Enter"> </FORM> </body></html>
Profile.aspx <html><body> Hello, <%= Request.QueryString("firstname") %> <%= Request.QueryString("lastname") %>. <br> You are <%= Request.QueryString("age") %> years old.<br> <% If Request.QueryString("userstatus") = "new" then Response.Write("This is your first visit to this Web site!") End if %> </body></html> http://localhost/aspsimple/profile.aspx? firstname=Jacky&lastname=Chan&age=45&userstatus=new&Submit1=Enter
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
Converting String to Number and Formatting <HTML><HEAD><title>WebForm1</title> <script language="vb" runat="server"> Sub EnterBtn_Click(Src As Object, e As EventArgs) Dim DollarInput as String Dim DollarConverted as Double Try DollarInput = Request.Params.Get("amount") DollarConverted = CType(DollarInput, Double) Response.Write("The amount you entered is=" & DollarConverted.ToString("C")) Catch ex as Exception Response.Write("You did not enter a proper dollar amount!") End Try End Sub </script> </HEAD> <body> <form id="Form1" method="post" runat="server" > <P>Enter the amount: <INPUT type="text" name="amount" size="20"></P> <INPUT type="submit" value="Submit" onserverclick="EnterBtn_Click" runat="server"> </form> </body> </HTML>
PostBack <formid="Form1"method="post" runat="server"> <form name="Form1" method="post" action="WebForm1.aspx" id="Form1"> WebForm1.aspx Design Run-time
Web Server Control Design <asp:TextBoxid="y"runat="server"></asp:TextBox> <input name="y" type="text" id="y" /> Run-time You should not add the name attribute to a Web Server Control. The name attribute will be added dynamically & automatically by ASP.NET Engine at runtime. The value of the name attribute will be the same as id attribute's value. Therefore, you can access to property of a textbox in multiple requests of a page via PostBack by its id, such as using y.Text to access the value entered by the user. You should use Request.Params.Get("y") to access the value entered by the user in the textbox in the target form action page when PostBack is not used.
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.
Formtest.htm <html> <body> <formaction="formtest.aspx"method="post"> <P>Your Name: <INPUTtype="text"NAME="GuestName"><br> Your age: <INPUTtype="text"NAME="Age"><br> <inputtype="checkbox"name="aspnet"value="on"> I like ASP.NET.<br> Choose Your Favorite Colors: <SELECTNAME="Colors"SIZE="3"MULTIPLE> <OPTIONvalue="B">Blue <OPTION>Red <OPTIONvalue="G"SELECTED>Green <OPTIONvalue="BR">Brown <OPTIONvalue="Y">Yellow</OPTION> </SELECT><BR> <inputtype="submit"value="Submit Query"> </form> </body></html>
Formtest.aspx <%@ Import namespace="System.Collections.Specialized" %> <!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <title>formtest</title> <metaname="GENERATOR"content="Microsoft Visual Studio.NET 7.0"> <metaname="CODE_LANGUAGE"content="Visual Basic 7.0"> <metaname="vs_defaultClientScript"content="JavaScript"> <metaname="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5"> <scriptrunat="server"> Private Sub Form_Handle() Dim x As NameValueCollection Dim keyArray As String() Dim fVariable As String Response.Write("<hr>Generalized Form Handling<hr>") x = Request.Form keyArray = x.AllKeys() For Each fVariable In keyArray Response.Write(fVariable & " = " & x.Get(fVariable) & "<br>") Next
Continued… Response.Write("<hr>Customized Form Handling<hr>") Response.Write("Guest name =<pre>" & _ Request.Form("GuestName").trim() & "!</pre><br>") Dim ageString As String Dim guestAge As Integer ageString = Request.Params("age") Response.Write("Age group = " & AgeGroup(ageString) & "<br>") ' Response.Write("Like ASP.NET = " & Request.Params("aspnet") & "<br>") If Request.Params("aspnet") Is Nothing Then Response.Write("Like ASP.NET = No" & "<br>") Else Response.Write("Like ASP.NET = Yes" & "<br>") End If Response.Write("Favorite Colors = <ul>") For Each fVariable In Request.Params.GetValues("colors") Response.Write("<li>" & fVariable) Next Response.Write("</ul>") End Sub
Continued… Private Function AgeGroup(ByVal InAge As String) As String Dim Age As Integer Dim group As String Try Age = Integer.Parse(InAge) If Age <= 0 Then group = "Undetermined group. (You entered an negative integer.)" ElseIf Age < 13 Then group = "pre-teen" ElseIf Age >= 13 And Age <= 19 Then group = "Teenager" ElseIf Age < 38 Then group = "Generation X" ElseIf Age < 50 Then group = "Baby Boomer" Else group = "Older Generation" End If Catch e As Exception group = "Undetermined group. (You did not enter an integer.)" End Try Return group End Function </script>
Continued… </HEAD> <body> <% Form_Handle() %> </body> </HTML>
String.Trim() • Removes all occurrences of a set of specified characters from the beginning and end of this instance. • Overload List • Removes all occurrences of white space characters from the beginning and end of this instance. • Overloads Public Function Trim() As String • Removes all occurrences of a set of characters specified in a Unicode character array from the beginning and end of this instance. • Overloads Public Function Trim(ParamArray Char()) As String
Formtest.aspx <%@ Page Language="vb" AutoEventWireup="false" Codebehind="FormTest.aspx.vb" Inherits="state.FormTest"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML><HEAD><title>FormTest</title></HEAD> <body> <form id="Form1" method="post" runat="server"> <P><asp:checkbox id="CheckBoxServerControl" runat="server" Text="Web Server Control"></asp:checkbox> </P> <P><INPUT id="CheckBoxHTMLControl" type="checkbox" Value="on" name="cb1" runat="server"> HTML Server Control</P> <P><INPUT id="Checkbox1" type="checkbox" name="cb2"> HTML Form Element</P> <P><asp:Button id="Button1" runat="server" Text="Submit"> </asp:Button></P> </form></body></HTML>
Formtest.asx.vb Public Class FormTest Inherits System.Web.UI.Page Protected WithEvents CheckBoxServerControl As System.Web.UI.WebControls.CheckBox Protected WithEvents CheckBoxHTMLControl As System.Web.UI.HtmlControls.HtmlInputCheckBox Protected WithEvents Button1 As System.Web.UI.WebControls.Button ….. Private Sub Page_Load (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Response.Write("<br>Web Server Control: " & CheckBoxServerControl.Checked) Response.Write("<br>Web HTML Control: " & CheckBoxHTMLControl.Checked) Response.Write("<br>HTML Form Element: " & Request.Params.Get("cb2")) If CheckBoxServerControl.Checked Then Response.Write("<br>You selected the Web Sevrer Control checkbox!") Else Response.Write("<br>Web Server Control checkbox:" & CheckBoxServerControl.Text) End If If CheckBoxHTMLControl.Checked Then Response.Write("<br>HTML Server Control checkbox:" &CheckBoxHTMLControl.Value) Else Response.Write("<br>You did not select the HTML Server Control checkbox!") End If If Request.Params.Get("cb2") <> "" Then ' Not (Request.Params.Get("cb2") Is Nothing) Response.Write("<br>You selected the form element checkbox!") Else Response.Write("<br>You did not select the form element checkbox!") End If End Sub End Class
Navigating Between Web Pages (Forms) • Hypertext links • Form submission • Request.Redirect()
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).