Form Handling and State Maintenance - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

Form Handling and State Maintenance

Description:

Form Handling and State Maintenance Major Build-in ASP.NET Objects State Maintenance Overview ViewState and Cookies Variables Application and Session Variables – PowerPoint PPT presentation

Number of Views:68
Avg rating:3.0/5.0
Slides: 31
Provided by: DanielFe8
Category:

less

Transcript and Presenter's Notes

Title: Form Handling and State Maintenance


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 Methodpost
greeting.htm
  • lthtmlgtltbodygt
  • ltform action"greeting.aspx" method"post"gt
  • Enter your name
  • ltinput type"text" name"guestName"gt ltbrgt
  • ltinput type"submit" value"Submit your name"gt
  • lt/formgtlt/bodygtlt/htmlgt

greeting.aspx
lthtmlgtltheadgtlttitlegtGreetingslt/titlegtlt/headgt ltbodygt
Hello lt request.form("guestName") gt
! lt/bodygtlt/htmlgt
6
Form Methodget
greeting2.htm
lthtmlgtltbodygt ltform action"greeting2.aspx"
method"get"gt Enter your name ltinput
type"text" name"guestName"gt ltbrgt ltinput
type"submit" value"Submit your
name"gt lt/formgtlt/bodygtlt/htmlgt
greeting2.aspx
lthtmlgtltheadgtlttitlegtGreetingslt/titlegtlt/headgt ltbodygt
Hello lt request.QueryString("guestName") gt
! lt/bodygtlt/htmlgt
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.

lthtmlgt ltbodygt ltFORM METHOD"GET"
ACTION"profile.aspx"gt First Name
ltINPUT TYPE"text" NAME"firstname"gtltbrgt
Last Name ltINPUT TYPE"text"
NAME"lastname"gtltbrgt Age ltINPUT
TYPE"text" NAME"age"gtltbrgt ltINPUT
TYPE"hidden" NAME"userstatus" VALUE"new"gt
ltINPUT TYPE"submit" VALUE"Enter"gt
lt/FORMgt lt/bodygtlt/htmlgt
8
Profile.aspx
http//localhost/aspsimple/profile.aspx? firstname
JackylastnameChanage45userstatusnewSubmit1
Enter
  • lthtmlgtltbodygt
  • Hello, lt Request.QueryString("firstname") gt
  • lt Request.QueryString("lastname") gt. ltbrgt
  • You are lt Request.QueryString("age") gt years
    old.ltbrgt
  • lt
  • If Request.QueryString("userstatus") "new"
    then
  • Response.Write("This is your first visit to
    this Web site!")
  • End if
  • gt lt/bodygtlt/htmlgt

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?categorybasicprice10
    0
  • 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
  • ltHTMLgtltHEADgtlttitlegtWebForm1lt/titlegt
  • ltscript language"vb" runat"server"gt
  • 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
  • lt/scriptgt
  • lt/HEADgt
  • ltbodygt
  • ltform id"Form1" method"post"
    runat"server" gt
  • ltPgtEnter the amount ltINPUT
    type"text" name"amount" size"20"gtlt/Pgt
  • ltINPUT type"submit" value"Submit"

12
PostBack
WebForm1.aspx
Design
  • ltform id"Form1" method"post"
  • runat"server"gt
  • ltform name"Form1" method"post"
    action"WebForm1.aspx" id"Form1"gt

Run-time
13
Web Server Control
Design
  • ltaspTextBox id"y" runat"server"gtlt/aspTextBoxgt
  • ltinput name"y" type"text" id"y" /gt

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?foodMelonfo
odWater20MelonfoodPineapple
15
List.aspx
  • ltHTMLgt
  • ltscript runatservergt
  • private sub foodlist()
  • Dim food As String
  • If Request.Params.GetValues("food") Is Nothing
    Then
  • Response.Write("None of the foods have been
    chosen!" "ltBRgt")
  • Else
  • For Each food In Request.Params.GetValues("foo
    d")
  • Response.Write(food "ltBRgt")
  • Next
  • End If
  • End Sub
  • lt/scriptgt
  • ltbodygt
  • lt foodlist() gt
  • lt/bodygt
  • lt/HTMLgt

16
foodform.aspx
  • lthtmlgtltheadgtlttitlegtFoodlt/titlegtlt/headgt
  • ltbodygt
  • ltform method"GET" action"list.aspx"gt
  • ltpgtltselect size"3" name"food" multiplegt
  • ltoptiongtApplelt/optiongt
  • ltoptiongtBreadlt/optiongt
  • ltoptiongtPineapplelt/optiongt
  • ltoptiongtOrangelt/optiongt
  • ltoptiongtRicelt/optiongt
  • lt/selectgtlt/pgt
  • ltpgt
  • ltinput type"submit" value"Submit"gt
  • ltinput type"reset" value"Reset"gtlt/pgt
  • lt/formgt
  • lta href"computer.aspx?idltServer.URLEncode("app
    le computer")gt"gt
  • I like apple computer lt/agtltbrgt
  • lta href"computer.aspx?idIntel computer"gtI like
    Intel computer lt/agt
  • lt/bodygtlt/htmlgt

17
computer.aspx
  • lthtmlgtltheadgtlttitlegt Computer lt/titlegtlt/headgt
  • ltbodygt
  • lt "The computer that you like " _
  • Request.querystring("ID") gt
  • lt/bodygtlt/htmlgt

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
  • lthtmlgt
  • ltbodygt
  • ltform action"formtest.aspx"
    method"post"gt
  • ltPgtYour Name ltINPUT type"text"
    NAME"GuestName"gtltbrgt
  • Your age ltINPUT type"text"
    NAME"Age"gtltbrgt
  • ltinput type"checkbox"
    name"aspnet" value"on"gt
  • I like ASP.NET.ltbrgt
  • Choose Your Favorite Colors
  • ltSELECT NAME"Colors" SIZE"3"
    MULTIPLEgt
  • ltOPTION value"B"gtBlue
  • ltOPTIONgtRed
  • ltOPTION value"G"
    SELECTEDgtGreen
  • ltOPTION value"BR"gtBrown
  • ltOPTION value"Y"gtYellowlt/OPTI
    ONgt
  • lt/SELECTgtltBRgt
  • ltinput type"submit"
    value"Submit Query"gt
  • lt/formgt
  • lt/bodygtlt/htmlgt

21
Formtest.aspx
  • lt_at_ Import namespace"System.Collections.Specializ
    ed" gt
  • lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN"gt
  • ltHTMLgt
  • ltHEADgt
  • lttitlegtformtestlt/titlegt
  • ltmeta name"GENERATOR" content"Microsoft
    Visual Studio.NET 7.0"gt
  • ltmeta name"CODE_LANGUAGE"
    content"Visual Basic 7.0"gt
  • ltmeta name"vs_defaultClientScript"
    content"JavaScript"gt
  • ltmeta name"vs_targetSchema"
    content"http//schemas.microsoft.com/intellisense
    /ie5"gt
  • ltscript runat"server"gt
  • Private Sub Form_Handle()
  • Dim x As NameValueCollection
  • Dim keyArray As String()
  • Dim fVariable As String
  • Response.Write("lthrgtGeneralized Form
    Handlinglthrgt")
  • x Request.Form
  • keyArray x.AllKeys()
  • For Each fVariable In keyArray
  • Response.Write(fVariable " "
    x.Get(fVariable) "ltbrgt")

22
Continued
  • Response.Write("lthrgtCustomized Form
    Handlinglthrgt")
  • Response.Write("Guest name ltpregt" _
  • Request.Form("GuestName").trim()
    "!lt/pregtltbrgt")
  • Dim ageString As String
  • Dim guestAge As Integer
  • ageString Request.Params("age")
  • Response.Write("Age group "
    AgeGroup(ageString) "ltbrgt")
  • ' Response.Write("Like ASP.NET "
    Request.Params("aspnet") "ltbrgt")
  • If Request.Params("aspnet") Is Nothing
    Then
  • Response.Write("Like ASP.NET No"
    "ltbrgt")
  • Else
  • Response.Write("Like ASP.NET Yes"
    "ltbrgt")
  • End If
  • Response.Write("Favorite Colors ltulgt")
  • For Each fVariable In Request.Params.GetVa
    lues("colors")
  • Response.Write("ltligt" fVariable)
  • Next
  • Response.Write("lt/ulgt")
  • 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 lt 0 Then
  • group "Undetermined group. (You
    entered an negative integer.)"
  • ElseIf Age lt 13 Then
  • group "pre-teen"
  • ElseIf Age gt 13 And Age lt 19 Then
  • group "Teenager"
  • ElseIf Age lt 38 Then
  • group "Generation X"
  • ElseIf Age lt 50 Then
  • group "Baby Boomer"
  • Else
  • group "Older Generation"
  • End If
  • Catch e As Exception

24
Continued
  • lt/HEADgt
  • ltbodygt
  • lt
  • Form_Handle()
  • gt
  • lt/bodygt
  • lt/HTMLgt

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
  • lt_at_ Page Language"vb" AutoEventWireup"false"
    Codebehind"FormTest.aspx.vb"
  • Inherits"state.FormTest"gt
  • lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN"gt
  • ltHTMLgtltHEADgtlttitlegtFormTestlt/titlegtlt/HEADgt
  • ltbodygt
  • ltform id"Form1" method"post"
    runat"server"gt
  • ltPgtltaspcheckbox id"CheckBoxServerCon
    trol" runat"server"
  • Text"Web Server Control"gtlt/aspcheckboxgtnbsp
    lt/Pgt
  • ltPgtltINPUT id"CheckBoxHTMLControl"
    type"checkbox" Value"on"
  • name"cb1" runat"server"gt HTML Server
    Controllt/Pgt
  • ltPgtltINPUT id"Checkbox1"
    type"checkbox" name"cb2"gt
  • HTML Form Elementlt/Pgt
  • ltPgtltaspButton id"Button1"
    runat"server" Text"Submit"gt
  • lt/aspButtongtlt/Pgt
  • lt/formgtlt/bodygtlt/HTMLgt

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("ltbrgtWeb Server Control "
    CheckBoxServerControl.Checked)
  • Response.Write("ltbrgtWeb HTML Control "
    CheckBoxHTMLControl.Checked)
  • Response.Write("ltbrgtHTML Form Element "
    Request.Params.Get("cb2"))
  • If CheckBoxServerControl.Checked Then
  • Response.Write("ltbrgtYou selected the
    Web Sevrer Control checkbox!")
  • Else
  • Response.Write("ltbrgtWeb Server
    Control checkbox" CheckBoxServerControl.Text)
  • End If
  • If CheckBoxHTMLControl.Checked Then
  • Response.Write("ltbrgtHTML Server
    Control checkbox" CheckBoxHTMLControl.Value)
  • Else
  • Response.Write("ltbrgtYou did not
    select the HTML Server Control checkbox!")

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

29
Hypertext Links and Forms
  • Hypertext link
  • lta href"URL?x3yHello"gtNextlt/agt
  • Forms
  • ltform action"URL" method"post"gt
  • Form elements
  • lt/formgt

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).
Write a Comment
User Comments (0)
About PowerShow.com