You are on page 1of 114

Introduction to ASP.

NET and Web Forms

Agenda
Background ASP.NET Overview Programming Model Programming Basics Server Controls Data Binding Conclusion

Slide 2 of 72

Background
Web Architecture
Client
Request: http://www.digimon.com/default.asp

PC/Mac/Unix/... + Browser

Network

HTTP, TCP/IP

Response: <html>.</html>

Server

Web Server

Slide 3 of 72

Background
Web Development Technologies
Client-side technologies

HTML, DHTML, JavaScript

Server-side technologies

ASP (Active Server Pages)

ASP.NET is the next generation of ASP

Slide 4 of 72

Background
What is ASP?
Server-side programming technology Consists of static HTML interspersed with script ASP intrinsic objects (Request, Response, Server, Application, Session) provide services Commonly uses ADO to interact with databases Application and session variables Application and session begin/end events ASP manages threads, database connections, ...
Slide 5 of 72

What is ASP?
Active Server Pages A series of objects and components that are executed on the web server Uses a suite of technologies that allows dynamically-generated content Control of how content is generated from the server to the browsers

Slide 6 of 72

HTML Page Execution


You Request an HTML Page www.ocstc.org/resumes.htm

Server finds and downloads the page

Browser displays the page

Slide 7 of 72

ASP Page Execution


You Request an ASP Page www.ocstc.org/default.asp

Server finds the page

Server executes ASP commands, converts ASP to HTML/XML as needed, processes HTML/XML

Browser displays the page

Slide 8 of 72

ASP Compared to Other Scripting Languages


ASP and /PHP/Perl/CGI execution are roughly equivalent in execution sequence Compared to VBScript, ASP does not have to worry about browser incompatibility Compared to JavaScript, dont have to worry about browser versions or disabling Compared to Java, dont have to worry about whether JRE (or MVM) is installed

Slide 9 of 72

ASP and XML


ASP can control the XML experience from beginning to end

Controls the output for conflicting browsers Generate XML data Logically connect XML and standalone databases Control data output formatting that XML or HTML cannot control

Slide 10 of 72

ASP in the Microsoft Language Family


The ASP commands...
Visual Basic

VBScript

ASP

But theres more to ASP than just code...


Slide 11 of 72

ASP in the Microsoft Language Family


Some characterize ASP as more or less server-side VBScript Arguments supporting this statement Arguments against this statement

Slide 12 of 72

ASP in the Microsoft Language Family


ASP can also interact with other Microsoft languages or applications:

Execute SQL commands Open and close databases Create and Modify database tables Control applications or COM objects written or compiled in other languages (VB, C++, Java) Extract content from Excel or Word Control an XML document

Slide 13 of 72

ASP Object Model


ASP itself is not Object-Oriented. ASP can use objects but cannot define new objects Composed of

5 objects 5 components

Slide 14 of 72

ASP Objects
Request Response Server Application Session

Slide 15 of 72

Code behind pages


Binds HTML page to a code file written in a .NET language HTML page is encapsulated in a System.Web.UI.Page class

Events such as Page_Load may be handled

All ASP.NET controls can be used as regular .NET objects Scripts in HTML page may call code behind functions Everything will eventually end up as HTML

Slide 16 of 72

Response and Request objects


Response

Represents the client browser


Response.Redirect(http://www.microsoft.com) Response.Cookies[UserName] = Bob

Request

Represents the server


Request.PhysicalApplicationPath UserName = (String)Request.Cookies[UserName]

Slide 17 of 72

Session and Application variables


Session variables

Hashtable-style collection of name-value pairs Remembered until the client closes the browser (or the session timeout expires default 20 minutes) Only for one client
Session[ValidUser] = true

Application variables

Hashtable-style collection of name-value pairs Always remembered For all clients


Application[NumClients] = NumClients + 1

Slide 18 of 72

ASP Components
Scripting Objects Component ADO (ActiveX Data Objects) Component Ad Rotator Component Browser Capabilities Component Content Linking Component

Slide 19 of 72

ASP Object Model


Server Request YOU ASP.DLL (if it finds <%%>, invokes Scripting Objects Component)

Response

Application Session

Slide 20 of 72

Background
What is ASP?
HTTP request
(form data, HTTP header data)

HTTP response
HTML, XML

ASP page
(static HTML, server-side logic)

Slide 21 of 72

ASP versus ASP.NET


ASP
Scripting language not compiled Blend of HTML and script on one page Developer needs to code all server-side actions

ASP.NET
Compiled code full language support Code behind page separate VB file Server-side controls handle most boiler-plate coding

Debugging difficult

Debugging runs in the IDE


ASP and ASP.NET can coexist on the same IIS Server
Slide 22 of 72

ASP.NET Namespaces Web


System.Web Core types that enable browser communication Types that provide caching support Types that affect the configuration of the web application configuration file

System.Web.Caching

System.Web.Configuration

Slide 23 of 72

ASP.NET Namespaces Security and UI


System.Web.Security Types that support security for a web application

System.Web.UI Types that provide ability to build System.Web.UI.WebControls GUI interfaces for a web application Systems.Web.UI.HTMLControls

Slide 24 of 72

ASP.NET Namespaces Web Services


System.Web.Services System.Web.Services.Discovery System.Web.Services.Description System.Web.Services.Protocols
Types that allow the building of Web Services

Slide 25 of 72

Slide 26 of 72

ASP Page vs. ASP Application


An ASP page

Needs the .ASP file extension to indicate to the server that there is code the server must interpret A series of commands on one page

An ASP application is a series of pages that are linked together through code and the content linking component to function as a logical unit

Slide 27 of 72

ASP Page vs. ASP Application


How the information is handled

Main communication device between pages and the server is by Forms Information can be transmitted or transferred from page to page in an application by

Submitting a form Sending a URL-encoded string www/ocstc.org/meetingadmin/edit.asp?ID=5 Storing data as a variable

Slide 28 of 72

Myths/Criticisms of ASP
ASP is Microsoft/Windows centric ASP doesnt work with Netscape ASP pages are not recognized by Search Engines ASP is slow because its interpreted (or because its Microsoft) ASP doesnt work with client-side scripting languages, especially JavaScript

Slide 29 of 72

Background
Demo: HelloWorld.asp
<html> <head><title>HelloWorld.asp</title></head> <body> <form method=post"> <input type="submit" id=button1 name=button1 value="Push Me" /> <% if (Request.Form("button1") <> "") then Response.Write("<p>Hello, the time is " & Now()) end if %> </form> </body> </html>
Slide 30 of 72

Background
ASP Successes
Simple procedural programming model Access to COM components

ActiveX Data Objects (ADO) File System Object Custom components VBScript, JScript leverages existing skills

Script-based: no compiling, just edit, save & run

Support for multiple scripting languages ASP has been very popular
Slide 31 of 72

Background
ASP Challenges
Coding overhead (too much code)

Everything requires writing code!

Code readability (too complex; code and UI intermingled) Maintaining page state requires more code Reuse is difficult Supporting many types of browsers is difficult Deployment issues (e.g. DLL locking) Session state scalability and availability Limited support for caching, tracing, debugging, etc. Performance and safety limitations of script
Slide 32 of 72

Agenda
Background ASP.NET Overview Programming Model Programming Basics Server Controls Data Binding Conclusion

Slide 33 of 72

ASP.NET Overview
ASP.NET provides services to allow the creation, deployment, and execution of Web Applications and Web Services Like ASP, ASP.NET is a server-side technology Web Applications are built using Web Forms Web Forms are designed to make building web-based applications as easy as building Visual Basic applications

Slide 34 of 72

ASP.NET Overview
Goals
Keep the good parts of ASP and improve the rest Simplify: less code, easier to create and maintain Multiple, compiled languages Fast Scalable Manageable Available Customizable and extensible Secure Tool support
Slide 35 of 72

ASP.NET Overview
Key Features

Web Forms Web Services Built on .NET Framework Simple programming model Maintains page state Multibrowser support XCOPY deployment XML configuration Complete object model

Session management Caching Debugging Extensibility Separation of code and UI Security ASPX, ASP side by side Simplified form validation Cookieless sessions

Slide 36 of 72

How Does ASP.NET Work?


When a browser requests an HTML file, the server returns the file When a browser requests an ASP.NET file, IIS passes the request to the ASP.NET engine on the server The ASP.NET engine reads the file, line by line, and executes the scripts in the file Finally, the ASP.NET file is returned to the browser as plain HTML
Slide 37 of 72

ASP.NET Overview
Demo: HelloWorld.aspx
<%@ Page Language="VB" %> <html> <head> <script runat="server"> sub B_Click (sender as object, e as System.EventArgs ) Label1.Text = "Hello, the time is " & DateTime.Now end sub </script> </head> <body> <form method="post" runat="server"> <asp:Button onclick="B_Click" Text="Push Me" runat="server" /> <p> <asp:Label id=Label1 runat="server" /> </form> </body> </html>
Slide 38 of 72

SERVERS
ASP.NET is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server. ASP.NET is a program that runs inside IIS IIS (Internet Information Services) is Microsoft's Internet server IIS comes as a free component with Windows servers IIS is also a part of Windows 2000 and XP Professional
Slide 39 of 72

ASP.NET Overview
Architecture
VB C++ C# JScript
Visual Studio.NET

Common Language Specification ASP.NET: Web Services and Web Forms Windows Forms

ADO.NET: Data and XML Base Classes Common Language Runtime

Slide 40 of 72

Agenda
Background ASP.NET Overview Programming Model Programming Basics Server Controls Data Binding Conclusion

Slide 41 of 72

Programming Model
Controls and Events
Server-side programming model Based on controls and events

Just like Visual Basic Not data in, HTML out

Higher level of abstraction than ASP Requires less code More modular, readable, and maintainable

Slide 42 of 72

Programming Model
Controls and Events

Button

Button code ... List code ... Text code ...

List

Text

Browser

ASP.NET

Event handlers

Slide 43 of 72

What Does ASP Look Like in Action?


What HTML looks like
<p>Analytical Ultracentrifugation Workshop (May 21-23, 2001) and Symposium (May 24, 2001) at the National Analytical Ultracentrifugation Facility, Storrs, Conn. For additional information</p> <ul> <li><a href="http://www.ucc.uconn.edu/~wwwbiotc/99wkshp.html" target="_blank"> National Analytical Ultracentrifugation Facility</a></li> <li><a href="naufworkshop.asp">Analytical Ultracentrifugation Workshop and Symposium Description and Registration (PDF Format)</a></li> </ul>

Slide 44 of 72

What Does ASP Look Like in Action?


What the real code looks like*
<% If Today < CDate("5/25/01") Then %> <p>Analytical Ultracentrifugation Workshop (May 21-23, 2001) and Symposium (May 24, 2001) at the National Analytical Ultracentrifugation Facility, Storrs, Conn. For additional information</p> <ul><li><a href="http://www.ucc.uconn.edu/~wwwbiotc/99wkshp.html" target="_blank">National Analytical Ultracentrifugation Facility</a></li> <li><a href="naufworkshop.asp">Analytical Ultracentrifugation Workshop and Symposium Description and Registration (PDF Format)</a></li> </ul> <% End If %>

* Coloring from Microsoft FrontPage


Slide 45 of 72

Tools You Need to Create ASP Applications


Web Server that Supports ASP

Microsoft Internet Information Server (IIS) Web services of Windows NT Server 4.0 and Windows 2000 Server Microsoft Personal Web Server (PWS) Creates a fully functional subset of IIS 4.0 that can run on all other Windows OS

PWS is an add-on for Windows NT, 95/98/Me Built-in to Windows 2000/XP PROFESSIONAL

Fundamental knowledge of Visual Basic

Slide 46 of 72

Programming Model
ASP.NET Object Model
User code executes on the web server in page or control event handlers Controls are objects, available in server-side code

Derived from System.Web.UI.Control Derived from System.Web.UI.Page which is a descendant of System.Web.UI.Control A page can have methods, properties, etc.
Slide 47 of 72

The web page is an object too

Programming Model
Postbacks
A postback occurs when a page generates an HTML form whose values are posted back to the same page A common technique for handling form data In ASP and other server-side technologies the state of the page is lost upon postback... Unless you explicitly write code to maintain state This is tedious, bulky and error-prone

Slide 48 of 72

Programming Model
Postbacks Maintain State
By default, ASP.NET maintains the state of all server-side controls during a postback Can use method="post" or method="get" Server-side control objects are automatically populated during postback No state stored on server Works with all browsers

Slide 49 of 72

Programming Model
Server-side Controls
Multiple sources of controls

Built-in 3rd party User-defined

Controls range in complexity and power: button, text, drop down, calendar, data grid, ad rotator, validation Can be populated via data binding

Slide 50 of 72

Programming Model
Automatic Browser Compatibility
Controls can provide automatic browser compatibility Can target UpLevel or DownLevel browsers

UpLevel browsers support additional functionality, such as JavaScript and DHTML DownLevel browsers support HTML 3.2

Slide 51 of 72

Programming Model
Automatic Browser Compatibility
IE 4
Button Menu Text

Netscape
Button Menu Text

Button Control

Button code ... Menu code ...

Menu Control

IE 5.5
Button Menu Text

Text Control

Text code ...

IE 6
Button Menu Text

ASP.NET

Event handlers

...
Slide 52 of 72

Programming Model
Code-behind pages
Two styles of creating ASP.NET pages

Controls and code in .aspx file Controls in .aspx file, code in code-behind page

Supported in Visual Studio.NET

Code-behind pages allow you to separate the user interface design from the code

Allows programmers and designers to work independently


<%@ Codebehind=WebForm1.bas Inherits=WebApplication1.WebForm1 %>
Slide 53 of 72

Programming Model
Automatic Compilation
Just edit the code and hit the page ASP.NET will automatically compile the code into an assembly Compiled code is cached in the CLR Assembly Cache Subsequent page hits use compiled assembly If the text of the page changes then the code is recompiled

Works just like ASP: edit, save and run


Slide 54 of 72

Programming Model
Automatic Compilation

Slide 55 of 72

Agenda
Background ASP.NET Overview Programming Model Programming Basics Server Controls Data Binding Conclusion

Slide 56 of 72

HTML CODE
<html> <head> <title>ASP.NET Hello World</title> </head> <body bgcolor="#FFFFFF"> <p>Hello World!</p> </body> </html>

Slide 57 of 72

CLASSIC ASP STYLE


<%@ Page Language="VB" %> <html> <head> <title>ASP.NET Hello World</title> </head> <body bgcolor="#FFFFFF"> <p><%= "Hello World!" %></p> </body> </html>
Slide 58 of 72

ASP.NET
<html> <head> <title>ASP.NET Hello World</title> </head> <body bgcolor="#FFFFFF"> <p>Hello World!</p> </body> </html>
Slide 59 of 72

Using Server Controls HTML Controls


<%@ Page Language="VB" %> <% HelloWorld.InnerText = "Hello World!%> <html> <head> <title>ASP.NET Hello World</title> </head> <body bgcolor="#FFFFFF"> <p id="HelloWorld" runat="server"></p> </body> </html>

Slide 60 of 72

Using Server Controls - Web Controls


<%@ Page Language="VB" %> <% HelloWorld.Text = "Hello World!" %> <html> <head> <title>ASP.NET Hello World</title> </head> <body bgcolor="#FFFFFF"> <p> <asp:label id="HelloWorld" runat="server" /> </p> </body> </html>
Slide 61 of 72

Using Server Controls Event Handlers


<%@ Page Language="VB" %> <script runat="server"> Sub Page_Load(Sender As Object, E As EventArgs) HelloWorld.Text = "Hello World! End Sub </script>
Slide 62 of 72

Cond.
<html> <head> <title>ASP.NET Hello World</title> </head> <body bgcolor="#FFFFFF"> <p><asp:label id="HelloWorld" runat="server" /></p> </body> </html>
Slide 63 of 72

Programming Basics
Page Syntax
The most basic page is just static text

Any HTML page can be renamed .aspx Directives: <%@ Page Language=VB %> Server controls: <asp:Button runat=server> Code blocks: <script runat=server></script> Data bind expressions: <%# %> Server side comments: <%-- --%> Render code: <%= %> and <% %>

Pages may contain:


Use is discouraged; use <script runat=server> with code in event handlers instead
Slide 64 of 72

Programming Basics
The Page Directive
Lets you specify page-specific attributes, e.g.

AspCompat: Compatibility with ASP Buffer: Controls page output buffering CodePage: Code page for this .aspx page ContentType: MIME type of the response ErrorPage: URL if unhandled error occurs Inherits: Base class of Page object Language: Programming language Trace: Enables tracing for this page Transaction: COM+ transaction setting

Only one page directive per .aspx file


Slide 65 of 72

Programming Basics
Server Control Syntax
Controls are declared as HTML tags with runat=server attribute
<input type=text id=text2 runat=server /> <asp:calendar id=myCal runat=server />

Tag identifies which type of control to create

Control is implemented as an ASP.NET class It names the instance available during postback Just like Dynamic HTML
Slide 66 of 72

The id attribute provides programmatic identifier


Programming Basics
Server Control Properties
Tag attributes map to control properties
<asp:button id=c1" Text="Foo" runat=server> <asp:ListBox id=c2" Rows="5" runat=server>

Tags and attributes are case-insensitive Control properties can be set programmatically
c1.Text = Foo c2.Rows = 5

Slide 67 of 72

Programming Basics
Maintaining State
By default. controls maintain their state across multiple postback requests

Implemented using a hidden HTML field: __VIEWSTATE Works for controls with input data (e.g. TextBox, CheckBox), non-input controls (e.g. Label, DataGrid), and hybrids (e.g. DropDownList, ListBox) Set EnableViewState=false Lets you minimize size of __VIEWSTATE
Slide 68 of 72

Can be disabled per control or entire page


Programming Basics
Maintaining State
Demo: MaintainingState.asp, MaintainingState.aspx

Slide 69 of 72

Programming Basics
Server Code Blocks
Server code lives in a script block marked runat=server
<script language="C#" runat=server> <script language="VB" runat=server> <script language="JScript" runat=server>

Script blocks can contain


Variables, methods, event handlers, properties They become members of a custom Page object

Slide 70 of 72

Programming Basics
Page Events
Pages are structured using events

Enables clean code organization Avoids the Monster IF statement Less complex than ASP pages e.g. Page_Load, Page_Unload Button1_Click Textbox1_Changed
Slide 71 of 72

Code can respond to page events

Code can respond to control events


Programming Basics
Page Event Lifecycle
Initialize Restore Control State Load Page Control Events
1. Change Events 2. Action Events Textbox1_Changed Button1_Click Page_Init Page_Load

Save Control State Render Unload Page

Page_Unload
Slide 72 of 72

Programming Basics
Page Loading
Page_Load fires at beginning of request after controls are initialized

Input control values already populated

protected sub Page_Load(s as Object, e as EventArgs) message.Text = "Howdy, World!" End sub

Slide 73 of 72

Programming Basics
Page Loading
Page_Load fires on every request

Use Page.IsPostBack to execute conditional logic If a Page/Control is maintaining state then need only initialize it when IsPostBack is false

protected sub Page_Load(s as Object, e as EventArgs) if (Page.IsPostBack) then else ' Executes only on initial page load Message.Text = "initial value" ' Rest of procedure executes on every request end sub
Slide 74 of 72

Programming Basics
Server Control Events
Change Events

By default, these execute only on next action event E.g. OnTextChanged, OnCheckedChanged Change events fire in random order Cause an immediate postback to server E.g. OnClick No client script required, no applets, no ActiveX Controls!
Slide 75 of 72

Action Events

Works with any browser

Programming Basics
Wiring Up Control Events
Control event handlers are identified on the tag
<asp:button onclick="btn1_click runat=server> <asp:textbox onchanged="text1_changed runat=server>

Event handler code


protected sub btn1_Click(s as Object, e as EventArgs) Message.Text = Button1 clicked end sub

Slide 76 of 72

Programming Basics
Event Arguments
Events pass two arguments:

The sender, declared as type object

Usually the object representing the control that generated the event Allows you to use the same event handler for multiple controls Provides additional data specific to the event EventArgs itself contains no data; a class derived from EventArgs will be passed

Arguments, declared as type EventArgs

Slide 77 of 72

Programming Basics
Page Unloading
Page_Unload fires after the page is rendered

Dont try to add to output

Useful for logging and clean up

protected sub Page_Unload(s as Object, e as EventArgs) MyApp.LogPageComplete() end sub

Slide 78 of 72

Programming Basics
Import Directive
Adds code namespace reference to page

Avoids having to fully qualify .NET types and class names Equivalent to the VB imports directive

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Net" %> <%@ Import Namespace="System.IO" %>

Slide 79 of 72

Programming Basics
Page Class
The Page object is always available when handling server-side events Provides a large set of useful properties and methods, including:

Application, Cache, Controls, EnableViewState, EnableViewStateMac, ErrorPage, IsPostBack, IsValid, Request, Response, Server, Session, Trace, User, Validators DataBind(), LoadControl(), MapPath(), Validate()
Slide 80 of 72

Agenda
Background ASP.NET Overview Programming Model Programming Basics Server Controls Data Binding Conclusion

Slide 81 of 72

Server Controls
ASP.NET ships with ~50 built-in controls Organized into logical families

HTML controls

Controls / properties map 1:1 with HTML Richer functionality More consistent object model

Web controls

Slide 82 of 72

Server Controls
HTML Controls
Work well with existing HTML designers Properties map 1:1 with HTML
table.bgcolor ="red"

Can specify client-side event handlers Good when quickly converting existing pages Derived from
System.Web.UI.HtmlControls.HtmlControl

Supported controls have custom class, others derive from HtmlGenericControl


Slide 83 of 72

Server Controls
HTML Controls
Supported controls

<a> <img> <form> <table> <tr> <td> <th> <select>

<textarea> <button> <input type=text> <input type=file> <input type=submit> <input type=button> <input type=reset> <input type=hidden>

Slide 84 of 72

Server Controls
HTML Controls
Demo 1: HTMLControls1.aspx

Basic page lifecycle with HTML Controls

Demo 2: HTMLControls2.aspx

More HTML Controls

Slide 85 of 72

Server Controls
HTML Controls
Can use controls two ways:

Handle everything in action events (e.g. button click)

Event code will read the values of other controls (e.g. text, check boxes, radio buttons, select lists)

Handle change events as well as action events

Slide 86 of 72

Server Controls
Web Controls
Consistent object model
Label1.BackColor = Color.Red Table.BackColor = Color.Blue

Richer functionality

E.g. AutoPostBack, additional methods

Automatic uplevel/downlevel support

E.g. validation controls


Enables better compiler type checking
Slide 87 of 72

Strongly-typed; no generic control

Server Controls
Web Controls
Web controls appear in HTML markup as namespaced tags Web controls have an asp: prefix
<asp:button onclick="button1_click runat=server> <asp:textbox onchanged="text1_changed runat=server>

Defined in the System.Web.UI.WebControls namespace This namespace is automatically mapped to the asp: prefix
Slide 88 of 72

Server Controls
Web Controls
Web Controls provide extensive properties to control display and format, e.g.

Font BackColor, ForeColor BorderColor, BorderStyle, BorderWidth Style, CssClass Height, Width Visible, Enabled

Slide 89 of 72

Server Controls
Web Controls
Four types of Web Controls

Intrinsic controls List controls Rich controls Validation controls

Slide 90 of 72

Server Controls
Intrinisic Controls
Correspond to HTML controls Supported controls

<asp:button> <asp:imagebutton> <asp:linkbutton> <asp:hyperlink> <asp:textbox> <asp:checkbox>

<asp:radiobutton> <asp:image> <asp:label> <asp:panel> <asp:table>

Slide 91 of 72

Server Controls
Intrinisic Controls
TextBox, ListControl, CheckBox and their subclasses dont automatically do a postback when their controls are changed Specify AutoPostBack=true to make change events cause a postback

Slide 92 of 72

Server Controls
List Controls
Controls that handle repetition Supported controls

<asp:dropdownlist> <asp:listbox> <asp:radiobuttonlist> <asp:checkboxlist> <asp:repeater> <asp:datalist> <asp:datagrid>


Slide 93 of 72

Server Controls
List Controls
Repeater, DataList and DataGrid controls

Powerful, customizable list controls Expose templates for customization Can contain other controls Provide event bubbling through their OnItemCommand event More about these controls and templates later

Slide 94 of 72

Server Controls
CheckBoxList & RadioButtonList
Provides a collection of check box or radio button controls Can be populated via data binding
<asp:CheckBoxList id=Check1 runat="server"> <asp:ListItem>Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> <asp:ListItem>Item 5</asp:ListItem> </asp:CheckBoxList>

Slide 95 of 72

Server Controls
Intrinisic & Simple List Controls
Demo 1: WebControls1.aspx

Assorted intrinsic and list controls

Demo 2: WebControls2.aspx

Same controls with AutoPostBack

Slide 96 of 72

Server Controls
Rich Controls
Custom controls with rich functionality Supported Controls

<asp:calendar> <asp:adrotator>

More will be added 3rd party controls are coming Demo: RichControls1.aspx

Slide 97 of 72

Server Controls
Validation Controls
Rich, declarative validation Validation declared separately from input control Extensible validation framework Supports validation on client and server

Automatically detects uplevel clients Avoids roundtrips for uplevel clients Prevents users from spoofing Web Forms

Server-side validation is always done

Slide 98 of 72

Server Controls
Validation Controls
<asp:RequiredFieldValidator>

Ensures that a value is entered Checks if value is within minimum and maximum values Compares value against constant, another control or data type Tests if value matches a predefined pattern Lets you create custom client- or server-side validation function Displays list of validation errors in one place
Slide 99 of 72

<asp:RangeValidator>

<asp:CompareValidator>

<asp:RegularExpressionValidator>

<asp:CustomValidator>

<asp:ValidationSummary>

Server Controls
Validation Controls
Validation controls are derived from
System.Web.UI.WebControls.BaseValidator,

which is derived from the Label control Validation controls contain text which is displayed only if validation fails Text property is displayed at control location ErrorMessage is displayed in summary

Slide 100 of 72

Server Controls
Validation Controls
Validation controls are associated with their target control using the ControlToValidate property
<asp:TextBox id=TextBox1 runat=server />
<asp:RequiredFieldValidator id="Req1" ControlToValidate="TextBox1" Text="Required Field" runat=server />

Can create multiple validation controls with the same target control
Slide 101 of 72

Server Controls
Validation Controls
Page.IsValid indicates if all validation controls on the page succeed
void Submit_click(s as object, e as EventArgs) if (Page.IsValid) then Message.Text = "Page is valid!" end if end sub

Slide 102 of 72

Server Controls
Validation Controls
Display property controls layout

Static: fixed layout, display wont change if invalid Dynamic: dynamic layout None: no display; can still use ValidationSummary and Page.IsValid

Type property specifies expected data type: Currency, Date, Double, Integer, String

Slide 103 of 72

Server Controls
Validation Controls
Can force down-level option

Only server-side validation


<% @ Page Language="c#" ClientTarget="DownLevel" %>

Slide 104 of 72

Server Controls
Validation Controls
Demo: ValidationControls1.aspx

Demonstrates each type of validation control

Slide 105 of 72

Agenda
Background ASP.NET Overview Programming Model Programming Basics Server Controls Data Binding Conclusion

Slide 106 of 72

Data Binding
How to Populate Server Controls?
Specify the data in the controls tags

Not dynamic: cant get data from a database

Write code that uses the controls object model

This is okay if you need to populate a simple value or list, but quickly gets too complicated for populating sophisticated displays Create an object that holds the data (DataSet, Array, string, int, etc.) Associate that object with the control
Slide 107 of 72

Data binding

Data Binding
What Is It?
Provides a single simple yet powerful way to populate Web Form controls with data

Enables clean separation of code from UI Properties, expressions, method calls Collections (Array, Hashtable, etc.) DataSet, DataTable, DataView, DataReader XML Requires code to reapply to data model
Slide 108 of 72

Supports binding to any data source


One way snapshot model

Data Binding
What Is It?
Allows you to specify an expression When the DataBind method of the control is called, the expression is evaluated and bound

DataBind for a single control (and subcontrols) Page.DataBind binds all controls on a page

Works for scalars, e.g. Label control Works for lists, e.g. DropDown control, ListBox control, etc. Enables the use of templates
Slide 109 of 72

Data Binding
Scalar Expressions
Data binding expression: <%# expression %> Expression is evaluated when DataBind() is called
<asp:Label id=label1 Text=<%# The result is & (1 + 2) & , the time is & DateTime.Now.ToLongTimeString() %> runat="server" /> public sub Page_Load(s as object, e as EventArgs) if (Page.IsPostBack) then else Page.DataBind() end if end sub
Slide 110 of 72

Data Binding
Scalar Expressions
Demo: DataBinding1.aspx

Data binding to simple, scalar expressions

Slide 111 of 72

Data Binding
Simple Lists
Data binding a list creates a user interface element for each item in the list Each item contains text (displayed to user) and an optional value (not displayed) The simple list controls:

<asp:ListBox>

Single or multiple select

<asp:DropDownList> <asp:RadioButtonList> <asp:CheckBoxList>


Slide 112 of 72

Data Binding
Simple Lists
Steps to data bind a list control

Declare the list control Optionally set DataValueField and DataTextField Set its DataSource Call DataBind() method

Slide 113 of 72

Data Binding
Simple Lists
Demo: DataBinding2.aspx

Data binding to simple lists

Slide 114 of 72

You might also like