1 / 30

Form Handling and State Maintenance

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

latika
Download Presentation

Form Handling and State Maintenance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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)

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

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

  4. Form Data Handling Without PostBack

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

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

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

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

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

  10. WebForm1.aspx

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

  12. PostBack <formid="Form1"method="post" runat="server"> <form name="Form1" method="post" action="WebForm1.aspx" id="Form1"> WebForm1.aspx Design Run-time

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

  14. Multiple Values of a Variable http://localhost/aspsimple/list.aspx?food=Melon&food=Water%20Melon&food=Pineapple

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

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

  17. computer.aspx <html><head><title> Computer </title></head> <body> <% = "The computer that you like: " _ & Request.querystring("ID") %> </body></html>

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

  19. Formtest.htm and Formtest.aspx

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

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

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

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

  24. Continued… </HEAD> <body> <% Form_Handle() %> </body> </HTML>

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

  26. 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>&nbsp;</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>

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

  28. Navigating Between Web Pages (Forms) • Hypertext links • Form submission • Request.Redirect()

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

  30. 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).

More Related