Vous êtes sur la page 1sur 41

ASP.

NET Introduction

What is ASP.NET?

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 Microsoft Technology


• ASP stands for Active Server Pages
• 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

What is an ASP.NET File?

• An ASP.NET file is just the same as an HTML file


• An ASP.NET file can contain HTML, XML, and scripts
• Scripts in an ASP.NET file are executed on the server
• An ASP.NET file has the file extension ".aspx"

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

What is ASP+?

ASP+ is the same as ASP.NET.

ASP+ is just an early name used by Microsoft when they developed ASP.NET.

The Microsoft .NET Framework

The .NET Framework is the infrastructure for the Microsoft .NET platform.

The .NET Framework is an environment for building, deploying, and running Web applications and
Web Services.

Microsoft's first server technology ASP (Active Server Pages), was a powerful and flexible
"programming language". But it was too code oriented. It was not an application framework and not
an enterprise development tool.

The Microsoft .NET Framework was developed to solve this problem.

.NET Frameworks keywords:


• Easier and quicker programming
• Reduced amount of code
• Declarative programming model
• Richer server control hierarchy with events
• Larger class library
• Better support for development tools

The .NET Framework consists of 3 main parts:

Programming languages:

• C# (Pronounced C sharp)
• Visual Basic (VB .NET)
• J# (Pronounced J sharp)

Server technologies and client technologies:

• ASP .NET (Active Server Pages)


• Windows Forms (Windows desktop solutions)
• Compact Framework (PDA / Mobile solutions)

Development environments:

• Visual Studio .NET (VS .NET)


• Visual Web Developer

This tutorial is about ASP.NET.

ASP.NET 2.0

ASP.NET 2.0 improves upon ASP.NET by adding support for several new features.

Differences between ASP and ASP.NET


ASP.NET has better language support, a large set of new controls and XML based
components, and better user authentication.

ASP.NET provides increased performance by running compiled code.

ASP.NET code is not fully backward compatible with ASP.

New in ASP.NET
 Better language support
 Programmable controls
 Event-driven programming
 XML-based components
 User authentication, with accounts and roles
 Higher scalability
 Increased performance - Compiled code
 Easier configuration and deployment
 Not fully ASP compatible

Language Support

ASP.NET uses the new ADO.NET.

ASP.NET supports full Visual Basic, not VBScript.

ASP.NET supports C# (C sharp) and C++.

ASP.NET supports JScript as before.

ASP.NET Controls

ASP.NET contains a large set of HTML controls. Almost all HTML elements on a page can be defined
as ASP.NET control objects that can be controlled by scripts.

ASP.NET also contains a new set of object oriented input controls, like programmable list boxes and
validation controls.

A new data grid control supports sorting, data paging, and everything you expect from a dataset
control.

Event Aware Controls

All ASP.NET objects on a Web page can expose events that can be processed by ASP.NET code.

Load, Click and Change events handled by code makes coding much simpler and much better
organized.

ASP.NET Components

ASP.NET components are heavily based on XML. Like the new AD Rotator, that uses XML to store
advertisement information and configuration.

User Authentication

ASP.NET supports forms-based user authentication, including cookie management and automatic
redirecting of unauthorized logins.

(You can still do your custom login page and custom user checking).
User Accounts and Roles

ASP.NET allows for user accounts and roles, to give each user (with a given role) access to different
server code and executables.

High Scalability

Much has been done with ASP.NET to provide greater scalability.

Server to server communication has been greatly enhanced, making it possible to scale an
application over several servers. One example of this is the ability to run XML parsers, XSL
transformations and even resource hungry session objects on other servers.

Compiled Code

The first request for an ASP.NET page on the server will compile the ASP.NET code and keep a
cached copy in memory. The result of this is greatly increased performance.

Easy Configuration

Configuration of ASP.NET is done with plain text files.

Configuration files can be uploaded or changed while the application is running. No need to restart
the server. No more metabase or registry puzzle.

Easy Deployment

No more server restart to deploy or replace compiled code. ASP.NET simply redirects all new
requests to the new code.

Compatibility

ASP.NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need
some changes to run under ASP.NET.

To overcome this problem, ASP.NET uses a new file extension ".aspx". This will make ASP.NET
applications able to run side by side with standard ASP applications on the same server.

Installing ASP.NET

A Windows Computer

ASP.NET is a Microsoft technology. To run ASP.NET you need a computer capable of running
Windows.
Windows 2000 or XP

If you are serious about developing ASP.NET applications you should install Windows 2000
Professional or Windows XP Professional.

In both cases, make sure you install the Internet Information Services (IIS) from the Add/Remove
Windows components dialog.

Service Packs and Updates

Before ASP.NET can be installed on your computer, it is necessary to have all relevant service packs
and security updates installed.

The easiest way to do this is to activate your Windows Internet Update. When you access the
Windows Update page, you will be instructed to install the latest service packs and all critical
security updates. For Windows 2000, make sure you install Service Pack 2. I will also recommend
that you install Internet Explorer 6.

ASP.NET - Server Controls

ASP.NET has solved the "spaghetti-code" problem described above with server controls.

Server controls are tags that are understood by the server.

There are three kinds of server controls:

 HTML Server Controls - Traditional HTML tags


 Web Server Controls - New ASP.NET tags
 Validation Server Controls - For input validation

ASP.NET - HTML Server Controls

HTML server controls are HTML tags understood by the server.

HTML elements in ASP.NET files are, by default, treated as text. To make these elements
programmable, add a runat="server" attribute to the HTML element. This attribute indicates that
the element should be treated as a server control. The id attribute is added to identify the server
control. The id reference can be used to manipulate the server control at run time.

Note: All HTML server controls must be within a <form> tag with the runat="server" attribute. The
runat="server" attribute indicates that the form should be processed on the server. It also indicates
that the enclosed controls can be accessed by server scripts.

In the following example we declare an HtmlAnchor server control in an .aspx file. Then we
manipulate the HRef attribute of the HtmlAnchor control in an event handler (an event handler is a
subroutine that executes code for a given event). The Page_Load event is one of many events that
ASP.NET understands:

<script runat="server">
Sub Page_Load
link1.HRef="http://www.w3schools.com"
End Sub
</script>
<html>
<body>
<form runat="server">
<a id="link1" runat="server">Visit W3Schools!</a>
</form>
</body>
</html>

The executable code itself has been moved outside the HTML.

ASP.NET - Web Server Controls

Web server controls are special ASP.NET tags understood by the server.

Like HTML server controls, Web server controls are also created on the server and they require a
runat="server" attribute to work. However, Web server controls do not necessarily map to any
existing HTML elements and they may represent more complex elements.

The syntax for creating a Web server control is:

<asp:control_name id="some_id" runat="server" />

In the following example we declare a Button server control in an .aspx file. Then we create an
event handler for the Click event which changes the text on the button:

<script runat="server">
Sub submit(Source As Object, e As EventArgs)
button1.Text="You clicked me!"
End Sub
</script>
<html>
<body>
<form runat="server">
<asp:Button id="button1" Text="Click me!"
runat="server" OnClick="submit"/>
</form>
</body>
</html>

ASP.NET - Validation Server Controls

Validation server controls are used to validate user-input. If the user-input does not pass validation,
it will display an error message to the user.

Each validation control performs a specific type of validation (like validating against a specific value
or a range of values).

By default, page validation is performed when a Button, ImageButton, or LinkButton control is


clicked. You can prevent validation when a button control is clicked by setting the CausesValidation
property to false.
ASP.NET – Events
ASP.NET - Event Handlers

Look at the following code:

<%
lbl1.Text="The date and time is " & now()
%>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

When will the code above be executed? The answer is: "You don't know..."

The Page_Load Event

The Page_Load event is one of many events that ASP.NET understands. The Page_Load event is
triggered when a page loads, and ASP.NET will automatically call the subroutine Page_Load, and
execute the code inside it:

<script runat="server">
Sub Page_Load
lbl1.Text="The date and time is " & now()
End Sub
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

Note: The Page_Load event contains no object references or event arguments!

Example

The Page.IsPostBack Property

The Page_Load subroutine runs EVERY time the page is loaded. If you want to execute the code in
the Page_Load subroutine only the FIRST time the page is loaded, you can use the Page.IsPostBack
property. If the Page.IsPostBack property is false, the page is loaded for the first time, if it is true,
the page is posted back to the server (i.e. from a button click on a form):

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
lbl1.Text="The date and time is " & now()
end if
End Sub
Sub submit(s As Object, e As EventArgs)
lbl2.Text="Hello World!"
End Sub
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
<h3><asp:label id="lbl2" runat="server" /></h3>
<asp:button text="Submit" onclick="submit" runat="server" />
</form>
</body>
</html>

The example above will write the "The date and time is...." message only the first time the page is
loaded. When a user clicks on the Submit button, the submit subroutine will write "Hello World!" to
the second label, but the date and time in the first label will not change.

Example
<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
lbl1.Text="The date and time is " & now()
end if
End Sub

Sub submit(s As Object, e As EventArgs)


lbl2.Text="Hello World!"
End Sub
</script>

<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
<h3><asp:label id="lbl2" runat="server" /></h3>
<asp:button text="Submit" onclick="submit" runat="server" />
</form>
</body>
</html>

Output Result
The date and time is 3/17/2009 1:47:08 AM
Submit

The example above will write the "The date and time is...." message only the first time the page is
loaded. When a user clicks on the Submit button, the submit subroutine will write "Hello World!" to
the second label, but the date and time in the first label will not change.

ASP.NET Web Forms


All server controls must appear within a <form> tag, and the <form> tag must contain
the runat="server" attribute.

Note : An .aspx page can only contain ONE <form runat="server"> control

Submitting a Form

A form is most often submitted by clicking on a button. The Button server control in ASP.NET has
the following format:

<asp:Button id="id" text="label" OnClick="sub" runat="server" />

The id attribute defines a unique name for the button and the text attribute assigns a label to the
button. The onClick event handler specifies a named subroutine to execute.

Example:
<script runat="server">
Sub submit(Source As Object, e As EventArgs)
button1.Text="You clicked me!"
End Sub
</script>

<html>
<body>

<form runat="server">
<asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit" />
</form>

</body>
</html>

Output Result :
Clickme!
ASP .NET Maintaining the ViewState
Maintaining the ViewState

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a
form with a lot of information and the server comes back with an error. You will have to go back to
the form and correct the information. You click the back button, and what happens.......ALL form
values are CLEARED, and you will have to start all over again! The site did not maintain your
ViewState.

When a form is submitted in ASP .NET, the form reappears in the browser window together with all
form values. How come? This is because ASP .NET maintains your ViewState. The ViewState
indicates the status of the page when submitted to the server. The status is defined through a
hidden field placed on each page with a <form runat="server"> control. The source could look
something like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">


<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />
.....some code
</form>

Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT
maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of
an .aspx page or add the attribute EnableViewState="false" to any control.

Look at the following .aspx file. It demonstrates the "old" way to do it. When you click on the
submit button, the form value will disappear:

<html>
<body>
<form action="demo_classicasp.aspx" method="post">
Your name: <input type="text" name="fname" size="20">
<input type="submit" value="Submit">
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!")
End If
%>
</body>
</html>

Example

Here is the new ASP .NET way. When you click on the submit button, the form value will NOT
disappear:

<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Hello " & txt1.Text & "!"
End Sub
</script>
<html>
<body>
<form runat="server">
Your name: <asp:TextBox id="txt1" runat="server" />
<asp:Button OnClick="submit" Text="Submit" runat="server" />
<p><asp:Label id="lbl1" runat="server" /></p>
</form>
</body>
</html>

Example (Click view source in the right frame of the example to see that ASP .NET has added a
hidden field in the form to maintain the ViewState)

Web Server Controls


Web server controls are special ASP.NET tags understood by the server.

Web Server Controls

Like HTML server controls, Web server controls are also created on the server and they require a
runat="server" attribute to work. However, Web server controls do not necessarily map to any
existing HTML elements and they may represent more complex elements.

The syntax for creating a Web server control is:

<asp:control_name id="some_id" runat="server" />

Web Server Control Description


AdRotator Displays a sequence of images
Button Displays a push button
Calendar Displays a calendar
CalendarDay A day in a calendar control
CheckBox Displays a check box
CheckBoxList Creates a multi-selection check box group
DataGrid Displays fields of a data source in a grid
DataList Displays items from a data source by using templates
DropDownList Creates a drop-down list
HyperLink Creates a hyperlink
Image Displays an image
ImageButton Displays a clickable image
Label Displays static content which is programmable (lets you apply styles to
its content)
LinkButton Creates a hyperlink button
ListBox Creates a single- or multi-selection drop-down list
ListItem Creates an item in a list
Literal Displays static content which is programmable(does not let you apply
styles to its content)
Panel Provides a container for other controls
PlaceHolder Reserves space for controls added by code
RadioButton Creates a radio button
RadioButtonList Creates a group of radio buttons
BulletedList Creates a list in bullet format
Repeater Displays a repeated list of items bound to the control
Style Sets the style of controls
Table Creates a table
TableCell Creates a table cell
TableRow Creates a table row
TextBox Creates a text box
Xml Displays an XML file or the results of an XSL transform

ASP.NET Button Control


Definition and Usage

The Button control is used to display a push button. The push button may be a submit button or a
command button. By default, this control is a submit button.

A submit button does not have a command name and it posts the Web page back to the server
when it is clicked. It is possible to write an event handler to control the actions performed when the
submit button is clicked.

A command button has a command name and allows you to create multiple Button controls on a
page. It is possible to write an event handler to control the actions performed when the command
button is clicked.

Properties
Property Description .NET
CausesValidation Specifies if a page is validated when a Button control is clicked 1.0
CommandArgument Additional information about the command to perform 1.0
CommandName The command associated with the Command event 1.0
OnClientClick The name of the function to be executed when the button is clicked 2.0
PostBackUrl The URL of the page to post to from the current page when the 2.0
Button control is clicked
runat Specifies that the control is a server control. Must be set to 1.0
"server"
Text The text on the button 1.0
UseSubmitBehavior A value indicating whether or not the Button control uses the client 2.0
browser's submit mechanism or the ASP.NET postback mechanism
ValidationGroup The group of controls for which the Button control causes validation 2.0
when it posts back to the server

Web Control Standard Properties


AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,
CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled,
SkinID, Style, TabIndex, ToolTip, Width

Example for Causes Validation


<html>
<body>

<form runat="server">
<asp:Button id="button1" Text="Cancel" CausesValidation="TRUE"
runat="server" />
</form>

</body>
</html>

Output :
Cancel

ASP.NET PostBackUrl Property


Definition and Usage

The PostBackUrl property is used to gets or sets the URL of the page to post when the Button
control is clicked.

Syntax
<asp:Button PostBackUrl="string" runat="server" />

Attribute Description
string String specifying the URL of the page to post to. Default is an empty string, this
causes the page to post back to itself

Example

The following example sets the post URL of a Button control:

<html>
<body>
<form runat="server">
Name:<asp:textbox id="TextBox1" runat=Server />
<asp:button id="Button1" Text="Submit"
PostBackUrl="demo_postbackurl.aspx" runat="Server" />
</form>
</body>
</html>

Output
Submit
Name:

ASP.NET Calendar Control


Definition and Usage

The Calendar control is used to display a calendar in the browser.

This control displays a one-month calendar that allows the user to select dates and move to the
next and previous months.

Properties
Property Description .NET
Caption The caption of the calendar 2.0
CaptionAlign The alignment of the caption text 2.0
CellPadding The space, in pixels, between the cell walls and contents 1.0
CellSpacing The space, in pixels, between cells 1.0
DayHeaderStyle The style for displaying the names of the days 1.0
DayNameFormat The format for displaying the names of the days 1.0
DayStyle The style for displaying days 1.0
FirstDayOfWeek What should be the first day of week 1.0
NextMonthText The text displayed for the next month link 1.0
NextPrevFormat The format of the next and previous month links 1.0
NextPrevStyle The style for displaying next and previous month links 1.0
OtherMonthDayStyle The style for displaying days that are not in the current month 1.0
PrevMonthText The text displayed for the previous month link 1.0
runat Specifies that the control is a server control. Must be set to 1.0
"server"
SelectedDate The selected date 1.0
SelectedDates The selected dates 1.0
SelectedDayStyle The style for selected days 1.0
SelectionMode How a user is allowed to select dates 1.0
SelectMonthText The text displayed for the month selection link 1.0
SelectorStyle The style for the month and weeks selection links 1.0
SelectWeekText The text displayed for the week selection link 1.0
ShowDayHeader A Boolean value that specifies whether the days of the week header 1.0
should be shown
ShowGridLines A Boolean value that specifies whether the grid lines between days 1.0
should be shown
ShowNextPrevMonth A Boolean value that specifies whether the next and previous 1.0
month links should be shown
ShowTitle A Boolean value that specifies whether the title of the calendar 1.0
should be shown
TitleFormat The format for the title of the calendar 1.0
TitleStyle The style of the title of the calendar 1.0
TodayDayStyle The style for today's date 1.0
TodaysDate Today's date 1.0
UseAccessibleHeader Specifying whether to use the <th> element for the day headers 2.0
instead of the <td> element
VisibleDate The date that specifies the month that is currently visible in the 1.0
calendar
WeekendDayStyle The style for weekends 1.0
OnDayRender The name of the function to be executed when when each day cell
is created
OnSelectionChanged The name of the function to be executed when the user selects a
day, week, or month
OnVisibleMonthChanged The name of the function to be executed when the user navigates
to a different month

ASP.NET SelectedDate Property


Definition and Usage

The SelectedDate property is used to get or set the selected date on a calendar.

<html>
<head>
<script language="VB" runat="server">
Sub Change(obj As Object, e As EventArgs)
Response.Write("Date: ")
Response.Write(cal1.SelectedDate.ToShortDateString())
End Sub
</script>
</head>

<body>
<form runat="server">
<asp:Calendar id="cal1" runat="server" OnSelectionChanged="Change" />
</form>
</body>
</html>
Output :
<
Marc
h >
2009
Sun Mon Tue Wed Thu Fri Sat
22 23 24 25 26 27 28
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 1 2 3 4

ASP.NET IsSelected Property


<html>
<head>
<script runat="server">
Sub DaySelect(obj As Object, e As DayRenderEventArgs)
If e.Day.IsSelected Then
If e.Day.IsOtherMonth = "TRUE" Then
Label1.Text = "NO"
Else
Label1.Text = "YES"
End If
End If
End Sub
</script>
</head>

<body>
<form runat="server">
<asp:Calendar id="cal1" runat="server" OnDayRender="DaySelect"/>
The selected date is in the current month:
<asp:Label id="Label1" runat="server"/>
</form>
</body>
</html>

<
Marc
h >
2009
Sun Mon Tue Wed Thu Fri Sat
22 23 24 25 26 27 28
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 1 2 3 4
The selected date is in the current month:
ASP.NET CheckBox Control
Definition and Usage

The CheckBox control is used to display a check box.

Properties
Property Description .NET
AutoPostBack Specifies whether the form should be posted immediately after the 1.0
Checked property has changed or not. Default is false
CausesValidation Specifies if a page is validated when a Button control is clicked 2.0
Checked Specifies whether the check box is checked or not 1.0
InputAttributes Attribute names and values used for the Input element for the 2.0
CheckBox control
LabelAttributes Attribute names and values used for the Label element for the 2.0
CheckBox control
runat Specifies that the control is a server control. Must be set to 1.0
"server"
Text The text next to the check box 1.0
TextAlign On which side of the check box the text should appear (right or 1.0
left)
ValidationGroup Group of controls for which the Checkbox control causes validation 2.0
when it posts back to the server
OnCheckedChanged The name of the function to be executed when the Checked
property has changed

ASP.NET Checked Property


<html>
<body>

<form runat="server">
<asp:CheckBox id="check1" Text="Is it?" Checked="TRUE" runat="server" />
</form>

</body>
</html>

Is it?

ASP.NET TextAlign Property


Definition and Usage
The TextAlign property is used to set or return the alignment of a checkbox text.

Default alignment is "right"

Syntax
<asp:CheckBox TextAlign="left|right" runat="server" />

<html>
<body>

<form runat="server">
<asp:CheckBox id="check1" runat="server" Text="Make it so" TextAlign="left" />
</form>

</body>
</html>

Make it so

ASP.NET CheckBoxList Control


Definition and Usage

The CheckBoxList control is used to create a multi-selection check box group.

Each selectable item in a CheckBoxList control is defined by a ListItem element!

Tip: This control supports data binding!

Properties
Property Description .NET
CellPadding The amount of pixels between the border and the contents of the 1.0
table cell
CellSpacing The amount of pixels between table cells 1.0
RepeatColumns The number of columns to use when displaying the check box 1.0
group
RepeatDirection Specifies whether the check box group should be repeated 1.0
horizontally or vertically
RepeatLayout The layout of the check box group 1.0
runat Specifies that the control is a server control. Must be set to 1.0
"server"
TextAlign On which side of the check box the text should appear

ASP.NET RepeatColumns Property


<html>
<body>
<form runat="server">
<asp:CheckBoxList id="lb1" runat="server" RepeatColumns="2">
<asp:ListItem Value="Item 1" />
<asp:ListItem Value="Item 2" />
<asp:ListItem Value="Item 3" />
<asp:ListItem Value="Item 4" />
</asp:CheckBoxList>
</form>
</body>
</html>

Item 1 Item 3
Item 2 Item 4

ASP.NET DropDownList Control


Definition and Usage

The DropDownList control is used to create a drop-down list.

Each selectable item in a DropDownList control is defined by a ListItem element!

Tip: This control supports data binding!

Properties
Property Description .NET
SelectedIndex The index of a selected item 1.0
OnSelectedIndexChanged The name of the function to be executed when the index of the 1.0
selected item has changed
runat Specifies that the control is a server control. Must be set to
"server"

ASP.NET SelectedIndex Property


Definition and Usage

The SelectedIndex property is used to get or set the index number of the selected item in a
DropDownList.

<html>
<head>
<script runat="Server">
Sub GetName(obj As Object, e As EventArgs)
lbl.Text = ddList.SelectedItem.Text
End Sub
</script>
</head>
<body>

<form runat="Server">
Select a name from the list:
<asp:DropDownList id="ddList" runat="Server">
<asp:ListItem Text="Peter" />
<asp:ListItem Text="Lois" />
<asp:ListItem Text="Cleveland" />
<asp:ListItem Text="Quagmire" />
<asp:ListItem Text="Joe" />
</asp:DropDownList>
<asp:Button Text="Select" OnClick="GetName" Runat="Server"/>
<br />
Name is:
<asp:Label id="lbl" Runat="Server"/><br/>
</form>
</body>
</html>

Select
Select a name from the list:
Name is:
ASP.NET HyperLink Control
Definition and Usage

The HyperLink control is used to create a hyperlink.

Properties
Property Description .NET
ImageUrl The URL of the image to display for the link 1.0
NavigateUrl The target URL of the link 1.0
runat Specifies that the control is a server control. Must be set to "server"1.0
Target The target frame of the URL 1.0
Text The text to display for the link

ASP.NET NavigateUrl Property


Definition and Usage

The NavigateURL property is used to set or return the URL of a HyperLink control.

Syntax
<asp:HyperLink NavigateUrl="URL" runat="server" />
Attribute Description
URL A string that specifies the URL of the hyperlink control

<html>
<body>

<form runat="server">
<asp:HyperLink id="link1" runat="server" Text="W3Schools"
NavigateUrl="http://www.w3schools.com" />
</form>

</body>
</html>

ASP.NET Image Control


Definition and Usage

The Image control is used to display an image.

Properties
Property Description .NET
AlternateText An alternate text for the image 1.0
DescriptionUrl The location to a detailed description for the image 2.0
GenerateEmptyAlternateTex Specifies whether or not the control creates an empty string as 2.0
t an alternate text
ImageAlign Specifies the alignment of the image 1.0
ImageUrl The URL of the image to display for the link 1.0
runat Specifies that the control is a server control. Must be set to
"server"

Example
<html>
<body>

<form runat="server">
<asp:Image
runat="server"
AlternateText="W3Schools"
ImageUrl="/banners/w6.gif"/>
</form>
</body>
</html>

ASP.NET ImageButton Control


Definition and Usage

The ImageButton control is used to display a clickable image.

Properties
Property Description .NET
CausesValidation Specifies if a page is validated when an ImageButton control is 1.0
clicked
CommandArgument Additional information about the command to perform 1.0
CommandName The command associated with the Command event 1.0
GenerateEmptyAlternateTex Specifies whether or not the control creates an empty string as 2.0
t an alternate text
OnClientClick The name of the function to be executed when the image is 2.0
clicked
PostBackUrl The URL of the page to post to from the current page when the 2.0
ImageButton control is clicked
runat Specifies that the control is a server control. Must be set to 1.0
"server"
TagKey 1.0
ValidationGroup The group of controls for which the ImageButton control causes 2.0
validation when it posts back to the server

Note: The properties of the Image control can also be used on the ImageButton control.

Example
<script runat="server">
Sub getCoordinates(sender As Object, e As ImageClickEventArgs)
mess.Text="Coordinates: " & e.x & ", " & e.y
End Sub
</script>

<html>
<body>

<form runat="server">
<p>Click on the image:</p>
<asp:ImageButton
runat="server"
ImageUrl="smiley.gif"
OnClick="getCoordinates"/>
<p><asp:label id="mess" runat="server"/></p>
</form>

</body>
</html>

Output

Click on the image:

ASP.NET LinkButton Control


Definition and Usage

The LinkButton control is used to create a hyperlink button.

Note: This control looks like a HyperLink control but has the same functionality as the Button
control.

Properties
Property Description .NET
CausesValidation Specifies if a page is validated when a LinkButton control is clicked 1.0
CommandArgument Additional information about the command to perform 1.0
CommandName The command associated with the Command event 1.0
OnClientClick The name of the function to be executed when the LinkButton is 2.0
clicked
PostBackUrl The URL of the page to post to from the current page when the 2.0
LinkButton control is clicked
runat Specifies that the control is a server control. Must be set to 1.0
"server"
Text The text on the LinkButton 1.0
ValidationGroup The group of controls for which the LinkButton control causes
validation when it posts back to the server

<script runat="server">
Sub lblClick(sender As Object, e As EventArgs)
Label1.Text="You clicked the LinkButton control"
End Sub
</script>

<html>
<body>

<form runat="server">
<asp:LinkButton Text="Click me!" OnClick="lblClick" runat="server" />
<p><asp:Label id="Label1" runat="server" /></p>
</form>

</body>
</html>

Output
Click me!

ASP.NET ListBox Control


Complete Web Control Reference

Definition and Usage

The ListBox control is used to create a single- or multi-selection drop-down list.

Each selectable item in a ListBox control is defined by a ListItem element!

Tip: This control supports data binding!

Properties
Property Description .NET
Rows The number of rows displayed in the list 1.0
SelectionMode Allows single or multiple selections

<script runat="server">
Sub submit(Sender As Object,e As EventArgs)
mess.Text="You selected " & drop1.SelectedItem.Text
End Sub
</script>

<html>
<body>

<form runat="server">
<asp:ListBox id="drop1" rows="3" runat="server">
<asp:ListItem selected="true">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:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
<asp:Button Text="Submit" OnClick="submit" runat="server" />
<p><asp:label id="mess" runat="server" /></p>
</form>
</body>
</html>

Output

Submit

ASP.NET ListItem Control

Definition and Usage

The ListItem control creates an item in a list.

This control is used with the list controls such as <asp:ListBox>, <asp:RadioButtonList> and
<asp:BulletedList>

Syntax
<asp:ListItem
Enabled="True|False"
Selected="True|False"
Text="label"
Value="value" />

Properties
Property Description .NET
Attributes Optional. A collection of attribute name and value pairs for the 1.0
ListItem that are not directly supported by the class
Enabled Optional. Specifies if the item is enabled or disabled 2.0
Selected Optional. Specifies whether or not the item is selected 1.0
Text Optional. The text displayed in the ListItem 1.0
Value Optional. The value of the the ListItem.

This example shows a BulletedList control with two ListItems in an .aspx file.
<html>
<body>

<form runat="server">
<asp:BulletedList runat="server">
<asp:ListItem Text="Item1" />
<asp:ListItem Text="Item2" />
</asp:BulletedList>
</form>
</body>
</html>

• Item1
• Item2

This example shows a ListBox control with some ListItems in an .aspx file. The items in the
list uses different properties to show the ListItem text.

<html>
<body>

<form runat="server">
<asp:ListBox runat="server">
<asp:ListItem Text="Text1" />
<asp:ListItem Value="Text3" Text="Text1">Text2</asp:ListItem>
<asp:ListItem Value="Text3" />
</asp:ListBox>
</form>

</body>
</html>

ASP.NET Literal Control


Definition and Usage

The Literal control is used to display text on a page. The text is programmable.

Note: This control does not let you apply styles to its content!

Properties
Property Description .NET
Mode 2.0
runat Specifies that the control is a server control. Must be set to 1.0
"server"
Text Specifies the text to display
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
Literal1.Text="I love ASP.NET!"
End Sub
</script>

<html>
<body>

<form runat="server">
<asp:Literal id="Literal1" Text="I love ASP!" runat="server" />
<br /><br />
<asp:Button Text="Change Text" OnClick="submit" runat="server" />
</form>

</body>
</html>

Output :
I love ASP!

Change Text

ASP.NET Panel Control

Definition and Usage

The Panel control is used as a container for other controls.

Tip: This control is often used to generate controls by code and to display and hide groups of
controls.

Note: This control renders as an HTML <div> element in IE and as a <table> tag in Mozilla.

Properties
Property Description .NET
BackImageUrl Specifies a URL to an image file to display as a background for this 1.0
control
DefaultButton Specifies the ID of the default button in the Panel 2.0
Direction Specifies the content display direction of the Panel 2.0
GroupingText Specifies the caption for the group of controls in the Panel 2.0
HorizontalAlign Specifies the horizontal alignment of the content 1.0
runat Specifies that the control is a server control. Must be set to 1.0
"server"
ScrollBars Specifies the position and visibility of scroll bars in the Panel 2.0
Wrap Specifies whether the content should wrap or not
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
if check1.Checked then
panel1.Visible=false
else
panel1.Visible=true
end if
End Sub
</script>

<html>
<body>

<form runat="server">
<asp:Panel id="panel1"
runat="server" BackColor="#ff0000"
Height="100px" Width="100px">
Hello World!
</asp:Panel>
<asp:CheckBox id="check1"
Text="Hide Panel control"
runat="server"/>
<br /><br />
<asp:Button Text="Reload" runat="server" />
</form>

</body>
</html>

Output :

Hello World!
Hide Panel control

Reload

ASP.NET RadioButton Control


Definition and Usage

The RadioButton control is used to display a radio button.

Tip: To create a set of radio buttons using data binding, use the RadioButtonList control!
Properties
Property Description
AutoPostBack A Boolean value that specifies whether the form should be posted
immediately after the Checked property has changed or not. Default is
false
Checked A Boolean value that specifies whether the radio button is checked or
not
id A unique id for the control
GroupName The name of the group to which this radio button belongs
OnCheckedChanged The name of the function to be executed when the Checked property
has changed
runat Specifies that the control is a server control. Must be set to "server"
Text The text next to the radio button
TextAlign On which side of the radio button the text should appear (right or left)

<script runat="server">
Sub submit(Sender As Object, e As EventArgs)
if red.Checked then
Label1.Text="You selected " & red.Text
elseIf green.Checked then
Label1.Text="You selected " & green.Text
elseIf blue.Checked then
Label1.Text="You selected " & blue.Text
end if
End Sub
</script>

<html>
<body>

<form runat="server">
Select your favorite color:
<br />
<asp:RadioButton id="red" Text="Red" Checked="True"
GroupName="colors" runat="server"/>
<br />
<asp:RadioButton id="green" Text="Green"
GroupName="colors" runat="server"/>
<br />
<asp:RadioButton id="blue" Text="Blue"
GroupName="colors" runat="server"/>
<br />
<asp:Button text="Submit" OnClick="submit" runat="server"/>
<p><asp:Label id="Label1" runat="server"/></p>
</form>

</body>
</html>
Select your favorite color:
Red
Green
Blue
Submit

ASP.NET BulletedList Control


Definition and Usage

The BulletedList control creates a list in bullet format.

Each item in a BulletedList control is defined by a ListItem element!

Note: This class is new in ASP.NET 2.0.

Properties
Property Description .NET
BulletImageUrl Specifies the URL of a custom bullet list image. Used if "BulletStyle" 2.0
is "CustomImage"
BulletStyle Specifies the style of the bullet list 2.0
DisplayMode Specifies the type of list displayed 2.0
FirstBulletNumber Specify the start number of list items in an ordered list 2.0
runat Required. Specifies that the control is a server control. Must be set 1.0
to "server"
Target Specifies where to open the target URL
<script runat="server">
Sub Check(sender As Object, e As EventArgs)
dim i
mess.Text="<p>Selected Item(s):</p>"
for i=0 to check1.Items.Count-1
if check1.Items(i).Selected then
mess.Text+=check1.Items(i).Text + "<br />"
end if
next
End Sub
</script>

<html>
<body>

<form runat="server">
<asp:CheckBoxList id="check1" AutoPostBack="True"
TextAlign="Right" OnSelectedIndexChanged="Check"
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:ListItem>Item 6</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:label id="mess" runat="server"/>
</form>

</body>
</html>

Item 1
Item 2
Item 3
Item 4
Item 5
Item 6

ASP.NET Style Control


Complete Web Control Reference

Definition and Usage

The Style control is used to set the style of a web control.

Properties
Property Description .NET
BackColor The background color of the control 1.0
BorderColor The border color of the control 1.0
BorderStyle The border style of the control 1.0
BorderWidth The border width of the control 1.0
CssClass The CSS class rendered by the control on the client 1.0
Font The font properties of the control 1.0
ForeColor The foreground color (typically the color of the text) of the control 1.0
Height The height of the control 1.0
RegisteredCssClass The CSS class that is registered with the control 2.0
Width The width of the control
ASP.NET Table Control

Definition and Usage

The Table control is used in conjunction with the TableCell control and the TableRow control to
create a table.

Properties
Property Description .NET
BackImageUrl A URL to an image to use as an background for the table 1.0
Caption The caption of the table 2.0
CaptionAlign The alignment of the caption text 2.0
CellPadding The space between the cell walls and contents 1.0
CellSpacing The space between cells 1.0
GridLines The gridline format in the table 1.0
HorizontalAlign The horizontal alignment of the table in the page 1.0
Rows A collection of rows in the Table 1.0
runat Specifies that the control is a server control. Must be set to
"server"

<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
dim rows,cells,j,i
rows=3
cells=2
For j=0 To rows-1
dim r As New TableRow()
For i=0 To cells-1
dim c As New TableCell()
c.Controls.Add(New LiteralControl("row " & j & ", cell " & i))
r.Cells.Add(c)
Next
Table1.Rows.Add(r)
Next
End Sub
</script>

<html>
<body>

<form runat="server">
<asp:Table id="Table1" BorderWidth="1" GridLines="Both" runat="server" />
</form>

</body>
</html>
row 0, cell 0 row 0, cell 1
row 1, cell 0 row 1, cell 1
row 2, cell 0 row 2, cell 1

ASP.NET TableCell Control

Definition and Usage

The TableCell control is used in conjunction with the Table control and the TableRow control to
create a cell in a table.

Tip: The cells of each row are stored in the Cells collection of the TableRow control.

Properties
Property Description .NET
AssociatedHeaderCellID A list of table header cells associated with the TableCell control 2.0
ColumnSpan The number of columns this cell should span 1.0
HorizontalAlign The horizontal alignment of the contents in the table cell 1.0
RowSpan The number of rows this cell should span 1.0
runat Specifies that the control is a server control. Must be set to 1.0
"server"
Text Specifies the text of the table cell 1.0
VerticalAlign The vertical alignment of the contents in the table cell 1.0
Wrap Specifies whether the cell's contents should wrap or not 1.0

Complete Web Control Reference

Definition and Usage

The XML control is used to display an XML document or the results of an XSL Transform.

Note: At least one of the XML Document properties must be set or no XML document is displayed.

You can also specify an XSLT document that will format the XML document before it is written to the
output. You can format the XML document with the Transform property or the TransformSource
property.

Properties
Property Description .NET
ClientID
Controls
Document Deprecated. Specifies an XML document using a 1.0
System.Xml.XmlDocument object
DocumentContent Specifies an XML string 1.0
DocumentSource Specifies a path to an XML file to display 1.0
EnableTheming
runat Specifies that the control is a server control. Must be set to 1.0
"server"
SkinID
Transform Formats the XML document using a System.Xml.Xsl.XslTransform 1.0
object
TransformArgumentList
TransformSource Specifies a path to an XSL Transform file

<html>
<body>

<form runat="server">
<asp:Xml DocumentSource="cdcatalog.xml" TransformSource="cdcatalog.xsl"
runat="server" />
</form>

<p><a href="cdcatalog.xml" target="_blank">View XML file</a></p>


<p><a href="cdcatalog.xsl" target="_blank">View XSL file</a></p>

</body>
</html>

My CD Collection
Title Artist
Empire Burlesque Bob Dylan
Hide your heart Bonnie Tyler
Greatest Hits Dolly Parton
Still got the blues Gary Moore
Eros Eros Ramazzotti

View XML file

View XSL file


XML File1
<?xml version="1.0" encoding="ISO-8859-1" ?>
- <!--
Edited by XMLSpy®
-->
- <catalog>
- <cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
- <cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
<company>CBS Records</company>
<price>9.90</price>
<year>1988</year>
</cd>
- <cd>
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<country>USA</country>
<company>RCA</company>
<price>9.90</price>
<year>1982</year>
</cd>
- <cd>
<title>Still got the blues</title>
<artist>Gary Moore</artist>
<country>UK</country>
<company>Virgin records</company>
<price>10.20</price>
<year>1990</year>
</cd>
- <cd>
<title>Eros</title>
<artist>Eros Ramazzotti</artist>
<country>EU</country>
<company>BMG</company>
<price>9.90</price>
<year>1997</year>
</cd>
</catalog>

XSL File
<?xml version="1.0" encoding="ISO-8859-1" ?>
- <!--
Edited by XMLSpy®
-->
- <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
- <xsl:template match="/">
- <html>
- <body>
<h2>My CD Collection</h2>
- <table border="1">
- <tr bgcolor="#9acd32">
<th align="left">Title</th>
<th align="left">Artist</th>
</tr>
- <xsl:for-each select="catalog/cd">
- <tr>
- <td>
<xsl:value-of select="title" />
</td>
- <td>
<xsl:value-of select="artist" />
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

ASP.NET 2.0 - New Features

ASP.NET 2.0 improves ASP.NET by adding several new features.


Improvements in ASP.NET 2.0

ASP.NET 2.0 was designed to make web development easier and quicker.

Design goals for ASP.NET 2.0:

• Increase productivity by removing 70% of the code


• Use the same controls for all types of devices
• Provide a faster and better web server platform
• Simplify compilation and installation
• Simplify the administration of web applications

What's New in ASP.NET 2.0?

Some of the new features in ASP.NET 2.0 are:

• Master Pages, Themes, and Web Parts


• Standard controls for navigation
• Standard controls for security
• Roles, personalization, and internationalization services
• Improved and simplified data access controls
• Full support for XML standards like, XHTML, XML, and WSDL
• Improved compilation and deployment (installation)
• Improved site management
• New and improved development tools

The new features are described below.

Master Pages

ASP.NET didn't have a method for applying a consistent look and feel for a whole web site.

Master pages in ASP.NET 2.0 solves this problem.

A master page is a template for other pages, with shared layout and functionality. The master page
defines placeholders for content pages. The result page is a combination (merge) of the master
page and the content page.

Read more about master pages.

Themes

Themes is another feature of ASP.NET 2.0. Themes, or skins, allow developers to create a
customized look for web applications.

Design goals for ASP.NET 2.0 themes:

• Make it simple to customize the appearance of a site


• Allow themes to be applied to controls, pages, and entire sites
• Allow all visual elements to be customized

Web Parts

ASP.NET 2.0 Web Parts can provide a consistent look for a site, while still allowing user
customization of style and content.

New controls:

• Zone controls - areas on a page where the content is consistent


• Web part controls - content areas for each zone

Navigation

ASP.NET 2.0 has built-in navigation controls like

• Site Maps
• Dynamic HTML menus
• Tree Views

Security

Security is very important for protecting confidential and personal information.

In ASP.NET 2.0 the following controls has been added:

• A Login control, which provides login functionality


• A LoginStatus control, to control the login status
• A LoginName control to display the current user name
• A LoginView control, to provide different views depending on login status
• A CreateUser wizard, to allow creation of user accounts
• A PasswordRecovery control, to provide the "I forgot my password" functionality

Roles and Personalization

Internet communities are growing very popular.

ASP.NET 2.0 has personalization features for storing user details. This provides an easy way to
customize user (and user group) properties.

Internationalization

Reaching people with different languages is important if you want to reach a larger audience.

ASP.NET 2.0 has improved support for multiple languages.

Data Access
Many web sites are data driven, using databases or XML files as data sources.

With ASP.NET this involved code, and often the same code had to be used over and over in different
web pages.

A key goal of ASP.NET 2.0 was to ease the use of data sources.

ASP.NET 2.0 has new data controls, removing much of the need for programming and in-depth
knowledge of data connections.

Mobility Support

The problem with Mobile devices is screen size and display capabilities.

In ASP.NET, the Microsoft Mobile Internet Toolkit (MMIT) provided this support.

In ASP.NET 2.0, MMIT is no longer needed because mobile support is built into all controls.

Images

ASP.NET 2.0 has new controls for handling images:

• The ImageMap control - image map support


• The DynamicImage control - image support for different browsers

These controls are important for better image display on mobile devices, like hand-held computers
and cell phones.

Automatic Compilation

ASP.NET 2.0 provides automatic compilation. All files within a directory will be compiled on the first
run, including support for WSDL, and XSD files.

Compiled Deployment (Installation) and Source Protection

ASP.NET 2.0 also provides pre-compilation. An entire web site can be pre-compiled. This provides
an easy way to deploy (upload to a server) compiled applications, and because only compiled files
are deployed, the source code is protected.

Site Management

ASP.NET 2.0 has three new features for web site configuration and management:

• New local management console


• New programmable management functions (API)
• New web-based management tool

Development Tools
With ASP.NET Visual Studio.NET was released with project and design features targeted at
corporate developers.

With ASP.NET 2.0, Visual Studio 2005 was released.

Key design features for Visual Studio 2005 include:

• Support for the features described above


• Upload files from anywhere (FTP, File System, Front Page....)
• No project files, allowing code to be manipulated outside Visual Studio
• Integrated Web Site Administration Tool
• No "build" step - ability to compile on first run

Visual Web Developer is a new free ASP.NET 2.0 tool for non-corporate developers who don't
have access to Visual Studio.NET.

Login Controls
How to: Create an ASP.NET Login Page

You can create a login page using the ASP.NET Login control. This control takes a user name and
password and uses ASP.NET membership and forms authentication to verify the user's credentials and
create an authentication ticket. For information about configuring ASP.NET membership and forms
authentication, see Introduction to Membership.
To create a login page

1. Create an ASP.NET Web application that uses ASP.NET membership. For details and examples,

see Configuring an ASP.NET Application to Use Membership.


2. Create an ASP.NET Web page in your application named Login.aspx.

Note

By default, ASP.NET forms authentication is configured to work with a page named Login.aspx.
You can change the default login page name in the Web.config file for your application using the
LoginUrl property.

3. Add a Login control to the page.

4. Optionally set the control's DestinationPageUrl property to the name of the page that the user will

be redirected to after logging in. If you do not specify a value for the DestinationPageUrl
property, the user will be redirected to the originally requested URL after being authenticated.

The following example shows the markup for a Login control:

Copy Code
<asp:Login
ID="Login1"
runat="server"
DestinationPageUrl="~/MembersHome.aspx">
</asp:Login>

Vous aimerez peut-être aussi