Title: Form Handling and State Maintenance
1Form 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)
2Major 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
3State 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.
4Form Data Handling Without PostBack
5Form 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
6Form 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
7Profile.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
8Profile.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
9Query 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
10WebForm1.aspx
11Converting 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"
12PostBack
WebForm1.aspx
Design
- ltform id"Form1" method"post"
- runat"server"gt
-
- ltform name"Form1" method"post"
action"WebForm1.aspx" id"Form1"gt
Run-time
13Web 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.
14Multiple Values of a Variable
http//localhost/aspsimple/list.aspx?foodMelonfo
odWater20MelonfoodPineapple
15List.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
16foodform.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
17computer.aspx
- lthtmlgtltheadgtlttitlegt Computer lt/titlegtlt/headgt
- ltbodygt
- lt "The computer that you like " _
- Request.querystring("ID") gt
- lt/bodygtlt/htmlgt
18Request.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.
19Formtest.htm and Formtest.aspx
20Formtest.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
21Formtest.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")
22Continued
- 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
23Continued
- 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
24Continued
- lt/HEADgt
- ltbodygt
- lt
- Form_Handle()
- gt
- lt/bodygt
- lt/HTMLgt
25String.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
26Formtest.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
27Formtest.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!")
28Navigating Between Web Pages (Forms)
- Hypertext links
- Form submission
- Request.Redirect()
29Hypertext 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.
30Variable 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).