Introduction to ASP.
NET
Active Server Pages
Web Applications
The Client/Server model a computation model for PCs to connect to other
computers, like the monitor and mainframe architecture model.
Client sends a request
Server answers the requests
For Web based applications
Communication are through HTTP (Hypertext Transfer Protocol)
Client is a browser such as IE (Internet Explorer)
A browser displays pages defined using HTML tags (Hypertext, Markup Language)
Static pages not going to change
Dynamic pages formed dynamically according to the requests
Web Applications
The application itself is defined on a web server such as IIS (Internet
Information Services), which in turn may interact with other server such as a
Database Management System (DBMS) that is hosted on a database server.
Web Applications
Dynamic Pages
A dynamic page is generated each time it is called
The same page may be posted back to the server for processing.
Nevertheless, the page itself is stateless, i.e., it will not maintain the value
of a variable between each loading of the page.
Server-Side Code
What is server-side code?
Software that runs on the server, not the client
Receives input from
URL parameters
HTML form data
Can access server-side databases, e-mail servers, files,
mainframes, etc.
Dynamically builds a custom HTML response for a client
HTTP request
(form data,
HTTP
header data)
HTTP response
HTML, XML
ASP page
(static HTML,
server-side
logic)
ASP.NET Overview and Features
ASP.NET provides services to allow the creation, deployment, and execution of
Web Applications and Web Services
Web Applications are built using Web Forms
Web Forms are designed to make building web-based applications as easy as
building Visual Basic applications
Built on .NET Framework: any .NET programming language can be used (C#,
Visual Basic)
Complete object model Every web component can be expressed as object
Separation of code and UI
Maintains page state
Session management
Caching, Debugging, Extensibility
WebTime.aspx Example
Creating an ASP.NET Web Application using VS
Step 1: Creating the Web Application Project
Select File > New Web Site... and choose ASP.NET Empty Web Site in the
Templates pane.
Select File System from the drop-down list closest to Location.
Set the Language to Visual C#, and click OK.
WebTime.aspx Example
Add an ASPX file (i.e., Web Form)
Visual Studio creates a code-behind file named Default.aspx.cs.
Look at Toolbox displayed in the IDE when the project loads.
Standard and Data list of web controls.
Editing the WebTime.aspx
When the project loads for the first time, the Web Forms Designer displays
the autogenerated ASPX file in Source mode.
Design mode indicates the XHTML element where the cursor is currently
located.
You can also view both the markup and the web-page design at the same time
by using Split mode
Right click the ASPX file in the Solution Explorer
and select View Code to open the code-behind file.
WebTime.aspx Example
Lets create our first ASP.NET page using Visual Studio
1.
Modify title of the page
2.
Add a heading <h2>
3.
Look at the page in Design and Split modes
4.
Add a Label control from the Toolbox
5.
Change ID of the Label control
6.
Change some physical properties of the Label control
7.
Go to WebTime.aspx.cs file and add Page_Init function to set Text property of
the Label control
WebTime.aspx Example
Changing the Title of the Page
We change the pages title from the default Untitled Page to A Simple Web Form
Example.
Open the ASPX file in Source mode and modify the text between the <title> tags.
Alternatively, you can modify the Web Forms Title property in the Properties window.
To view the Web Forms properties, select DOCUMENT from the drop-down list in the
Properties window.
Designing the Page
To add controls to the page, you can drag and drop them from the Toolbox onto the
Web Form in Design mode.
Like the Web Form itself, each control is an object that has properties, methods and
events.
You can type text directly on a Web Form at the cursor location or insert XHTML
elements using menu commands.
Renaming the WebTime.aspx
Renaming the ASPX File
Right click the ASPX file in the Solution Explorer and select Rename.
Enter the new file name WebTime.aspx and press Enter. Both the ASPX file
and the code-behind file are updated.
Renaming the Class in the Code-Behind File and Updating the ASPX File
Visual Studios refactoring tool, which automatically updates
the existing
references to this class in the rest of the project to reflect this change.
Right click the class name in the partial classs declaration and select
Refactor > Rename to open the Rename dialog.
Visual Studio generates the markup
shown when you create the GUI.
The page directive specifies
information needed by
ASP.NET to process this file
The document type declaration,
which specifies the document
element name and the PUBLIC
URI for the DTD that defines the
XHTML vocabulary.
The form that contains our
XHTML text and controls is set
to execute on the server, which
generates equivalent XHTML.
The body contains
the main content
that the browser
displays.
XHTML documents have the
root element html and markup
information about the
document in the head element.
Visual Studio generates the markup
shown when you create the GUI.
The asp:tag prefix indicates
that the label is an ASP.NET web
control, not an XHTML element.
(Markup for a label web control)
In an ASPX file a directive is delimited by <%@ and %>
ASP.NET comments begin with <%-- and terminate with -%>, and can span multiple lines.
WebTime.aspx Example
Examining an ASPX File
The Page directives Language attribute specifies the code-behind files
language.
The CodeFile attribute specifies the code-behind filename.
When AutoEventWireup is true, ASP.NET automatically treats a method of
name Page_EventName as an event handler.
When AutoEventWireup is set to false, you specify event handlers using
attributes in the Page directive just as you would any other web control.
The Inherits attribute specifies the class in the code-behind file from which
this ASP.NET class inherits.
WebTime.aspx Example
The document type declaration, which specifies the document element name
and the PUBLIC URI for the DTD that defines the XHTML vocabulary.
XHTML documents have the root element html and markup information about
the document in the head element.
Setting the runat attribute to "server" indicates that ASP.NET processes the
element and its nested elements and generates the corresponding XHTML.
The body contains the main content that the browser displays.
The form that contains our XHTML text and controls is set to execute on the
server, which generates equivalent XHTML.
WebTime.aspx Example
The ID attribute assigns a name to a control, used as an identifier in the
code-behind file.
The asp: tag prefix indicates that the label is an ASP.NET web control, not an
XHTML element.
Each web control maps to a corresponding XHTML element or group of
elements.
WebTime.aspx Example
The asp:Label control is written as an XHTML span element.
A span element contains text with formatting styles.
This control is processed on the server so that the server can translate the
control into XHTML.
If this is not supported, the asp:Label element is written as text to the client.
The code-behind file (WebTime.aspx.cs)
The Page_Init method handles
the pages Init event, which
indicates that the page is ready
to be initialized.
Retrieve the current time and
formats it as hh:mm:ss.
WebTime.aspx Example Run
The Page_Init method handles the pages Init event, which indicates that the
page is ready to be initialized.
WebTime.aspx Example
> Relationship Between an ASPX File and a Code Behind File
The code-behind file inherits from Page, which defines the general
functionality of a web page.
The code-behind file contains a partial class.
ASP.NET generates another partial class that defines the remainder of that
class, based on the markup in the ASPX file.
The first time the web page is requested, this class is compiled, and an
instance is created.
This instance represents our pageit creates the XHTML that is sent to the
client.
Once an instance of the web page has been created, multiple clients can use
it to access the pageno recompilation is necessary.
WebTime.aspx Example
> How the Code in an ASP.NET Web Page Executes
When an instance of the page is created, the PreInit event occurs first,
invoking method Page_PreInit, which can be used to set a pages theme.
The Init event occurs next, invoking method Page_Init, which is used to
initialize objects and other aspects of the page.
Next, the Load event occurs, and the Page_Load event handler executes.
The page then processes any events that are generated by the pages
controls.
Once a response has been generated and sent, an Unload event occurs,
which calls Page_Unload, which typically releases resources used by the
page.
Further reading: https://msdn.microsoft.com/en-us/library/ms178472.aspx
WebTime.aspx Example
To view the XHTML generated by ASP.NET, select View Source from the Page
menu in Internet Explorer (or View > Page Source if you are using Firefox).
Nonvisual form components, called hidden inputs, store data that the user
doesnt need to see.
Attribute method of the form element specifies the request method (usually
get or post). The action attribute identifies the resource that will be
requested when a form is submitted.
XHTML generated by ASP.NET when web
browser requests WebTime.aspx
Attribute method of the form
element specifies the request
method (usually get or post). The
action attribute identifies the
resource that will be requested
when a form is submitted.
Non visual form components
called hidden inputs, store
data that the user doesnt need
to see.
XHTML generated by ASP.NET when web
browser requests WebTime.aspx
The form contains a span element
to represent the text in the label.
Formatting properties of
lblMyTimer are converted into the
style attribute of the span
element.
WebTime.aspx Example
When the form is processed on the server, the runat attribute is removed.
Only those elements marked in the ASPX file with runat=server are
modified or replaced in the generated XHTML.
WebTime.aspx Example
The positions of controls and other elements are relative to the Web Forms
upper-left corner. This type of layout is known as relative positioning.
An alternate type of layout is known as absolute positioning, in which
controls are located exactly where they are dropped on the Web Form.
Absolute positioning is discouraged, because pages designed in this manner
may not render correctly in different browsers or on computers with
different screen resolutions and font sizes.
Running WebTime.aspx Example
Running the Program
You can view the Web Form several ways.
You can select Debug > Start Without Debugging, which runs the application by
opening it in a browser window.
To debug your application, you can select Debug > Start Debugging. You cannot
debug a web application unless debugging is explicitly enabled by the web.config
file.
To view a specific ASPX file, you can right click either the Web Forms Designer or
the ASPX file name and select View In Browser.
Finally, you can run your application by opening a browser window and typing the
web pages URL in the Address field.
Event Handling
GUIs are event driven.
When the user interacts with a GUI component, the event drives the program
to perform a task.
A method that performs a task in response to an event is called an event
handler.
Event Handling Example (HelloWorld)
Lets create another ASP.NET page using Visual Studio
1.
Add a Button and a Label control
2.
To create this click event handler, double click the Button on the Form.
3.
The following empty event handler is declared:
4.
Set the Text property of the Label control with the current time in this function.
ASP.NET comments begin with <
%-- and terminate with --%>, and
can span multiple lines.
HelloWorld Example
<%-- Hello World page that also displays the current time. --%>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="HelloWorld.aspx.cs"
Inherits="HelloWorldPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
The Page directive specifies
information needed by ASP.NET to
process this file
<head runat="server">
<title>Hello World Web Form</title>
</head>
The body contains the main
content that the browser displays.
<body>
<form id="form1" runat="server">
<div>
XHTML documents have the root
element html and markup
information about the document
in the head element.
<asp:Button ID="buttonClick" runat="server" Font-Size="Medium"
Width="102px"
Text="Click Me" OnClick="BClick" />
<br />
<asp:Label ID="labelHello" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Markup for label & button web
controls.
The asp: tag prefix indicates that the label is an
ASP.NET web control, not an XHTML element.
ASPX Code Behind File
using System;
public partial class HelloWorldPage : System.Web.UI.Page
{
protected void BClick(object sender, EventArgs e)
{
labelHello.Text = "Hello World! Time is " +
DateTime.Now.ToString("HH:mm:ss");
}
}
Event Handling
By convention, C# names the event-handler method as
objectName_eventName (e.g., Button1_Click).
Each event handler receives two parameters when it is called:
An object reference named sender a reference to the object that generated the
event.
A reference to an object of type EventArgs, which contains additional information
about the event.
Other Ways to Create Event Handlers
Typically, controls can generate many different types of events.
Clicking the Events icon (the lightning-bolt icon) in the Properties window,
displays all the events for the selected control.
Programming Model Controls and Events
Button code
Button
...
List code
List
...
Label code
Label
Browser
...
ASP.NET
Event handlers
ASP.NET Architecture
VB
C++
C#
JScript
ASP.NET: Web Services
and Web Forms
Windows
Forms
ADO.NET: Data and XML
Base Classes
Common Language Runtime
Visual Studio.NET
Common Language Specification
Programming Model (ASP.NET Object
Model)
Controls are objects, available in server-side code
The web page is an object too
Derived from System.Web.UI.Control
Derived from System.Web.UI.Page
User code executes on the web server in page or control event handlers
Server Controls
ASP.NET ships with more than 50 built-in controls
Organized into logical families
HTML Controls
Controls / properties map 1:1 with HTML
Web Controls
Richer functionality
More consistent object model // the properties are changed in the consistent way loke
background
Server Controls
> HTML Controls
Works 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
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>
Server Controls
> HTML Controls
Demo 1
HTMLControls1.aspx
Basic Page Life Cycle with HTML Controls
Demo 2
HTMLControls2.aspx
More HTML Controls
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
Server Controls
> Web Controls
Consistent object model
Label1.BackColor = Color.Red;
Table.BackColor = Color.Blue;
Richer functionality
E.g. AutoPostBack, additional methods
AutoPostBack is the method by which the page will be posted back to the server
automatically based on some events in the web controls
Strongly-typed; no generic control
Enables better compiler type checking
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
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
Server Controls
> Web Controls
Four types of Web controls
Intrinsic controls
List controls
Rich controls
Validation controls
Server Controls
> Intrinsic Controls
Correspond to HTML controls
Supported controls
<asp:button>
<asp:label>
<asp:imagebutton>
<asp:panel>
<asp:linkbutton>
<asp:table>
<asp:hyperlink>
<asp:textbox>
<asp:checkbox>
<asp:radiobutton>
<asp:image>
Server Controls
> Intrinsic 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
Server Controls
> List Controls
Controls that handle repetition
Supported controls
<asp:dropdownlist>
<asp:repeater>
<asp:listbox>
<asp:datalist>
<asp:radiobuttonlist>
<asp:datagrid>
<asp:checkboxlist>
Repeater, DataList and DataGrid controls expose templates for customization
Server Controls
> CheckBoxList & RadioButtonList
Provides a collection of checkbox for 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>
Server Controls
> Intrinsic & Simple List Controls
Demo 1: WebControls1.aspx
Assorted intrinsic and list controls
Demo 2: WebControls2.aspx
Same controls with AutoPostBack