ASP.NET Forms

ASP.NET Forms
• An ASP.NET form is a HTML form plus asp.net
code in the form of server controls.
• ASP.NET form has extra functionality to maintain
form data or state (_VIEWSTATE plus
POSTBACK) eg text in a text box
– Hidden variable to store ‘coded’ version of the form
• ASP.NET server controls duplicate the functionality
of many HTML elements.
– Take the form of an html-like tag, marking the point in the
page where the server needs to generate corresponding
true HTML elements. (produces server side object that can
be manipulated at any part of the code.)
Example: datacontrol2.aspx
<%@ Page language="VB" runat="server" %>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.XML" %>
<script language="vb" runat="server">
Sub Page_Load()
Dim xmlFilename As String
xmlFilename= "C:\cse2030\jason1\artists.xml"
Dim newDataSet As New DataSet
newDataSet.ReadXML(xmlFilename)
DataGrid1.DataSource = newDataSet
DataGrid1.DataBind()
End Sub
</script>
<html> <head> <title>Data Grid Control example</title> </head>
<body>
<asp:DataGrid id="DataGrid1" runat="server" />
</body> </html>
Artists.xml
<?xml version="1.0"?>
<artist>
<item>
<name>Vincent Van Gogh</name>
<nationality>Dutch</nationality>
<movement>Post Impressionism </movement>
<birthdate>30th March 1853</birthdate>
</item>
<item>
<name>Paul Klee </name>
<nationality>Swiss </nationality>
<movement>Abstract Expressionism </movement>
<birthdate>18th December 1879</birthdate>
</item>
<item>
<name>Max Ernst </name>
<nationality>German </nationality>
<movement>Surrealism </movement>
<birthdate>2nd April 1891</birthdate>
</item>
</artist>
ASP.NET execution
• When a browser requests a web page, server
locates the page. If it has an .aspx extension, then
the server sends it to aspnet_isapi.dll which
forwards it to the CLR. The CLR compiles the
code (if it is a new page) and executes it to
produce html that is sent to the client.
• All the ASP.NET code can be in a separate file,
know as a code-behind page.
– quickstart-aspforms-example13
Web Forms
•
•
•
•
•
•
Server side controls
Generate output suitable for the browser
Preserves state across page refreshes (Viewstate)
Raise server side events
Used as the base to build richer controls
ASP.Net includes a range of useful classes and
namespaces
– Namespace is like a class library eg.
System.Web.UI.HtmlControls
– See class browser from last lecture
What are Server Controls?
• Server programmable objects
– have properties,events,methods that can be accessed at run time
(Use Visual Studio.Net at design time)
System.Web.UI.WebControls namespace
• denoted by Tag with the runat=“server” attribute
• render different HTML to support multiple browser types
(eg IE4 and above -rendering implemented on the client;
IE3 done by the server)
• Can create server control from HTML control by adding
the runat=“server” attribute
– eg <input type=“text” runat=“server”>
Server Side Controls
• HTMLControls
– System.Web.UI.HtmlControls namespace
– Can be directly mapped to HTML tags
– Used for backward compatibility with ASP
eg <input type=“text” runat=“server” id=“txtname” value=“mytext” >
• Web Controls
– System.Web.UI.WebControls namespace
– Form based event model eg buttonclick
– Offer a richer set of controls
• implement a number of common properties (properties through class
browser)
• data binding
• automatic browser detection
<asp:textbox id=“txtname” runat=“server” text=“mytext”>
• Programmatic reference of a control is by the unique id
attribute eg id=“txtname”
How do server controls work?
• Declared with the runat=“server” attribute
• when the aspx page is executed
– creates Action and Method attributes of the
form
– adds unique Id and Name attributes to controls
– adds Value attribute to controls
– adds a hidden control (_VIEWSTATE) to the
form to save form state information
Server control example
<script runat="server" language="vb">
Sub Page_Load()
if Request.Form("list1") <> "" then
Message.text = "You have selected " + Request.Form("list1")
end if
End Sub
</script>
<html> <head> <title>Drop Down List Example</title> </head>
<body>
<asp:label id="message" runat="server"/> <br />
<form runat="server">
<!– notice no action or method attributes -->
Which city do you wish to look at hotels for?<br /><br />
<asp:dropdownlist id="list1" runat="server">
<asp:listitem>Madrid</asp:listitem>
<asp:listitem>Oslo</asp:listitem>
<asp:listitem>Lisbon</asp:listitem>
</asp:dropdownlist> <br /><br /><br /><br />
<input type="Submit">
</form> </body> </html>
Server control example cont 2.
Server control example cont 3.
Server control eg. Cont. 4 – view source.
<html>
<head>
<title>Drop Down List Example</title>
</head>
<body>
<span id="message">You have selected Lisbon</span>
<br />
<form name="_ctl0" method="post" action="listpage.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwtMTMyNTU5Mzc0Njt0PDtsPGk8MT47PjtsPHQ8cDxwPGw8VGV4dDs+
O2w8WW91IGhhdmUgc2VsZWN0ZWQgTGlzYm9uOz4+Oz47Oz47Pj47PtM3XxNyv
4v6En+WgxP4D5/iJj1M" />
Which city do you wish to look at hotels for?<br /><br />
<select name="list1" id="list1">
<option value="Madrid">Madrid</option>
<option value="Oslo">Oslo</option>
<option selected="selected" value="Lisbon">Lisbon</option>
</select> <br /><br /><br /><br />
<input type="Submit">
</form> </body> </html>
Server control eg. Cont. 5 - Notes
• All output from server to browser is HTML
• New attributes added to form tag
–
–
–
–
<form name="_ctl0" method="post" action="listpage.aspx" id="_ctl0">
Post is the asp.net default method
Action attribute points to the same page (listpage.aspx)
A hidden control stores the state of the page
<input type="hidden" name="__VIEWSTATE"
value="dDwtMTMyNTU5Mzc0Njt0PDtsPGk8MT47PjtsPHQ8cDxwPGw8VGV4dDs+
O2w8WW91IGhhdmUgc2VsZWN0ZWQgTGlzYm9uOz4+Oz47Oz47Pj47PtM3XxNyv
4v6En+WgxP4D5/iJj1M" />
– Used by asp.net to keep track of all server control settings from one page
refresh to another; otherwise listbox would revert to static default setting
every time page is loaded. Very useful for data validation.
HTML controls demo
– demo server_controls.aspx (note form state is lost; cf:
server_controlsM.aspx – same controls but with
runat=“server”)
<%@ Page Language="vb" %>
<HTML>
<body> <form>
Name: <input type="text"> <P>
Profession: <select>
<option>Software Engineer</option>
<option>Software Tester</option>
<option>Program Manager</option>
</select>
<p>
<input type="submit" value="Save">
</form>
</body> </html>
Web Controls
• There are five types of controls
–
–
–
–
–
Intrinsic Controls eg asp:list, asp:button etc
List Controls eg asp:datagrid, asp:datarepeater
Rich Controls eg asp:calander
Validation Controls eg asp:rangeValidator
Custom Controls – user defined
• They support properties, methods and
events
• System.Web.UI.WebControls namespace
Intrinsic Controls
• Executed on the server side
• Accessed via properties/attributes
– (some common to all controls eg text,
backcolor and other specific eg checked=true
for a checkbox)
•
•
•
•
Have associated events
Can maintain state information.
Output is standard HTML
Prefixed with the tag ‘asp’ (cf. HTML controls
don’t have this tag)
Intrinsic Controls (2)
HTML Output
ASP.NET Intrinsic Controls
<select>…</select>
<asp:DropDownList>
<td>…</td>
<asp:TableCell>
<tr>…</tr>
<asp:TableRow>
<table>…</table>
<asp:Table>
<div>…</div>
<asp:Panel>
<span>…</span>
<asp:Label>
<img src=“…”>
<asp:Image>
<select size=“…”>…</select> <asp:ListBox>
<input type=“radio”>
<asp:RadioButton>
<input type=“checkbox”>
<asp:CheckBox>
<input type=“text” value=“…”> <asp:TextBox>
<a href=“…”>…</a>
<asp:HyperLink>
<input type=“image”>
<asp:ImageButton>
<a href=“jscript:__doPostBack(…)”>…</a> <asp:LinkButton>
<input type=“submit”>
<asp:Button>
Intrinsic Controls (3)
Sample Server Side Code
<asp:ListBox runat=“server”>
<asp:ListItem>Test1</asp:ListItem>
<asp:ListItem>Test3</asp:ListItem>
</asp:ListBox>
Sample Client Side Result
<select name=ListBox0>
<option value=“Test1”>Test1</option>
<option value=“Test3”>Test3</option>
</select>
Two syntax forms:
<asp:label id=“message1” forecolor=“red” runat=“server”> Hello </asp:label>
Is the same as
<asp:label id=“message1” forecolor=“red” runat=“server” text=“Hello”/>
List Controls
• Displaying lists of data.
• Also supports additional functionality, including
sorting, filtering, selecting items.
• Five types (next lecture; datacontrol2.aspx-slide 2)
– Repeater – Just renders a repeated list
– DataList – Like Repeater but with additional formatting
functionality
– DataGrid – Produces data in a Grid format, but also
provides functionality for data editing.
– RadioButtonList – Renders the list with RadioButtons
associated with each data item.
– CheckboxList – Renders the list with CheckBoxes
associated with each data item.
(Discuss next lecture)
Rich Controls
• Ever growing list of Rich Controls
• EG.
– Calendar
– TreeView
– ImageGenerator
– AdRotator
– Etc
(Discuss next lecture)
Validation Controls
• One of the common tasks of scripts has been
validating data entered on the web page
• ASP.NET simplifies validation via a number of
controls (can be either client or server based; can
have more than one for a control; triggered by events eg
textchange)
–
–
–
–
–
RequiredFieldValidator
CompareValidator
RangeValidator
RegularExpressionValidator
CustomValidator
Web Control Events
• Each web control has a number of events
(onClick…etc)
• There are events associated with server
events (Page_load..etc)
• Each event results in a reload of the page
via a postback
• A web control is associated to an event by
setting its attributes - the name of the
function which implements the event
handler.
HTML Control
Server Event Handlers
• Client-side controls have events such as onClick
and onChange are associated with HTML client
controls
– To be able to detect these events on the server, Visual
Studio .NET will create a generic JavaScript event
handler called _doPostBack
– The event sends the name of the control (eventTarget)
and any arguments (eventArgument) back to the server
when the event is intercepted
– This handler only is required once per page, and is
written by the server, not the programmer
• OnServerChange event occurs when an HTML
server control value has changed
Sample Web Form
<input name="WebAddress" type="text"
id="WebAddress"
onchange="__doPostBack('WebAddress','')"
language="javascript" />
<input type="submit" name="GoBtn"
value="Go" id="GoBtn" />
<input type="hidden"
name="__EVENTTARGET" value="" />
<input type="hidden"
name="__EVENTARGUMENT" value="" />
Sample _doPostback
Event Handler
<script language="javascript">
<!-function __doPostBack(eventTarget, eventArgument) {
var theform = document.ctrl0;
theform.__EVENTTARGET.value = eventTarget;
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>
Page event life cycle
• In ASP.NET a structured set of events occurs
every time a page is viewed. The order is:
– Page_init (done once; useful for variable initialisation)
– Page_load (can be used to load data into controls from
server DB) see POSTBACK
– Change events eg textbox1_changed; by default only
click events submit form to the server; change events
are queued till then. (Some controls have an
AUTOPOSTBACK property which will force a post)
– Click event eg button1_click
– Page_Unload (last event before page is discarded eg
user going to another page; useful for closing files, db’s
etc
Event example
<%@ Page Language="vb" %>
<HTML> <body>
<SCRIPT language="VB" runat="Server">
Sub GreetMe(s As Object, e As EventArgs)
label1.Text = "Hello " & txtName.Value & _
". I see your occupation is " & lstTitle.Value
End Sub
</SCRIPT>
<FORM runat="server">
Name: <INPUT type="text" id="txtName" runat="server">
<p>Profession: <SELECT id="lstTitle" runat="server">
<OPTION> Software Engineer </OPTION>
<OPTION> Software Tester </OPTION>
<OPTION> Program Manager </OPTION>
</SELECT>
<p><INPUT type="Submit" Value="Save" onServerClick="GreetMe" runat="server">
<p><asp:label id="label1" runat="server"/>
</FORM> </body> </html>
Event example cont.
What is PostBack?
• A PostBack is as result of a event within the ASP.NET
being triggered. This is opposed to a page request.
• Using Page.IsPostBack you can determine whether the
event is as a result of a Web Control event or a request
for the page.
• Since Web Controls implement ViewState (A Web
Control remembers content regardless of the number of
refreshes), there is no need to requery a database, just to
populate controls.
• PostBack offers the ability to only execute code that is
required, not the entire ASP+ script.
Postback example
<%@ Page Language="vb" %>
<HTML> <body>
<SCRIPT language="VB" runat="Server">
Sub GreetMe(s As Object, e As EventArgs)
label1.Text = "Hello " & txtName.Value & _
". I see your occupation is " & lstTitle.Value
End Sub
Sub Page_Load(s As Object, e As EventArgs)
If Not Page.IsPostBack Then
txtName.Value = "Enter your name"
End If
End Sub
</SCRIPT>
<FORM runat="server">
Name: <INPUT type="text" id="txtName" runat="server">
<p>Profession: <SELECT id="lstTitle" runat="server">
<OPTION> Software Engineer </OPTION>
<OPTION> Software Tester </OPTION>
<OPTION> Program Manager </OPTION>
</SELECT>
<p><INPUT type="Submit" Value="Save" onServerClick="GreetMe" runat="server">
<p><asp:label id="label1" runat="server"/>
</FORM> </body> </html>
Another example-holidaypage.aspx.
<html> <head> <title>Holiday page</title> </head> <body>
<form action="holidayresponse.aspx" method="post">
<h1>Feiertag Holidays</h1>
Please enter your details here. <br /><br />
Name:<asp:textbox id="FullName" runat="server" />
<br /><br />
Address:<asp:textbox id="Address" rows="5" textmode="multiline" runat="server" />
<br /><br />
Sex <asp:radiobuttonlist id="sex" runat="server">
<asp:listitem value="Male" />
<asp:listitem value="Female" />
</asp:radiobuttonlist>
Please select the destination you would like details on:
<asp:dropdownlist id="Destination" runat="server">
<asp:listitem value="Madrid" />
<asp:listitem value="Barcelona"/>
<asp:listitem value="Lisbon"/>
<asp:listitem value="Oslo"/>
<asp:listitem value="Prague"/>
Please enter your details here.
</asp:dropdownlist>
<br /><br />
<br /><br />
Name:<input type="text" id="FullName"
<input type="Submit">
runat="server" />
<input type="Reset">
<br /><br />
</form> </body> </html>
This will not work because
<asp:..> don’t work unless they
are in the form with
runat=“server”. But this stops us
using a different form action.
Use HTML controls instead.
Another eg. cont 1-holidayresponse.aspx.
<script runat="server" language="vb">
Sub Page_Load()
Response.Write ("<b>Name:</b> " + Request.Form("FullName") + "<br />")
Response.Write ("<b>Address:</b> " + Request.Form("Address") + "<br />")
Response.Write ("<b>Sex:</b> " + Request.Form("Sex") + "<br />")
Response.Write ("<b>Destination:</b> " + Request.Form("Destination") + "<br />")
End Sub
</script>
<html>
<head>
<title>Holiday page</title>
</head>
<body>
<br /><br />
These details have been entered into our database, you should receive a confirmation email from us
shortly.
<br /><br />
</body> </html>
Validation controls revisited
• Properties of the validation control
– Control to validate (id of control)
– Error message
– Display (static or dynamic as to where the error message is displayed)
Name: <asp:textbox id="txtName" runat="server" />
……
<asp:RequiredFieldValidator id="txtNameValidator" runat="server"
controlToValidate="txtName"
errorMessage="You must enter your name"
display="dynamic">
</asp:RequiredFieldValidator>
Validation Control eg1.validation.aspx
<%@ Page language="vb" %>
<HTML>
<body>
<SCRIPT language="VB" runat="Server">
Sub submit(s As Object, e As EventArgs)
spnOutputButton.InnerHTML = "Button clicked. Textbox value is " &
txtName.Text
End Sub
Sub lst_change(s As Object, e As EventArgs)
spnOutputList.InnerHTML = "Listbox changed to " &
lstTitle.SelectedItem.Value
End Sub
Sub Page_load(s As Object, e As EventArgs)
lblListbox.DataBind()
End Sub
</SCRIPT>
Validation Control example 2.
<FORM runat="server">
Name: <asp:textbox id="txtName" runat="server" />
<asp:RequiredFieldValidator id="txtNameValidator" runat="server"
controlToValidate="txtName"
errorMessage="You must enter your name"
display="dynamic">
</asp:RequiredFieldValidator>
<asp:RangeValidator id="txtNameRngValidator" runat="server"
controlToValidate="txtName"
errorMessage="Please enter a name that begins with 'A'"
type="String"
minimumValue="A"
maximumValue="B"
display="dynamic">
</asp:RangeValidator>
Validation Control example 3.
<p>Profession: <asp:dropdownlist autopostback=True id="lstTitle"
onselectedindexchanged="lst_change" runat="server" >
<asp:listitem>Program Manager</asp:listitem>
<asp:listitem>Tester</asp:listitem>
<asp:listitem>User Assistance</asp:listitem>
</asp:dropdownlist>
<p><asp:Button Text="Save" onclick="submit" runat="server" ID=Button1/>
<asp:label id="lblListbox" runat=Server text="<%# lstTitle.selecteditem.text %>" />
<p><span style="color:red;" id="spnOutputList" runat="server"></span>
<p><span style="color:red;" id="spnOutputButton" runat="server"></span>
</form>
</body>
</html>
<HTML>
<body>
<form name="_ctl0" method="post" action="validation.aspx" language="javascript"
onsubmit="ValidatorOnSubmit();" id="_ctl0">
….
<script language="javascript">
<!-function __doPostBack(eventTarget, eventArgument) {
var theform = document._ctl0;
theform.__EVENTTARGET.value = eventTarget;
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>
Code Behind
• Allows for the separation of server side
code and HTML
• Create a class file that inherits from
ASP.NET Page class
– Done automatically by VS.NET
User Controls
• Can be used to write ‘include files’ to create
consistent look and feel
• End with .ascx
• Included with
<%@ Register TagPrefix="UserControl"
TagName="Header" Src="header.ascx" %>
• Used with
<UserControl:Header id="MyHeader" runat="Server" />
• TagPrefix and TagName
• See example source usercontroleg.txt
• Demo
Configuration and Deployment
• Configuration details are in a text file called
web.config that is structured in XML
format. This is in the site’s root folder
• All files that a Web application needs are in
folder under the site’s root folder and DLL’s
are in the /bin folder (don’t have to register
in the Registry; only need to copy)
/wwwroot
/webapplication1 - aspx, web.config
/bin - dll’s
/webapplication2 - aspx, web.config
/bin - dll’s