7/30/2019 asp.net eamples
1/21
ASP.NET 2.0 Tutorial
What's New in ASP.NET 2.0?
ASP.NET is a programming framework built on the common language runtime that can
be used on a server to build powerful Web applications. The first version of ASP.NEToffered several important advantages over previous Web development models. ASP.NET
2.0 improves upon that foundation by adding support for several new and excitingfeatures in the areas of developer productivity, administration and management,extensibility, and performance:
Developer Productivity
ASP.NET 2.0 encapsulates common Web tasks into application services and controls that
can be easily reused across web sites. With these basic building blocks, many scenarios
can now be implemented with far less custom code than was required in previousversions. With ASP.NET 2.0 it is possible to significantly reduce the amount of code and
concepts necessary to build common scenarios on the web.
New Server Controls. ASP.NET 2.0 introduces many new server controls that
enable powerful declarative support for data access, login security, wizardnavigation, menus, treeviews, portals, and more. Many of these controls take
advantage of core application services in ASP.NET for scenarios like data access,
membership and roles, and personalization. Some of the new families of controls
in ASP.NET 2.0 are described below.
o Data Controls. Data access in ASP.NET 2.0 can be accomplished
completely declaratively (no code) using the new data-bound and data
source controls. There are new data source controls to represent different
data backends such as SQL database, business objects, and XML, andthere are new data-bound controls for rendering common UI for data, such
as gridview, detailsview, and formview..
o Navigation Controls. The navigation controls provide common UI for
navigating between pages in your site, such as treeview, menu, and
sitemappath. These controls use the site navigation service in ASP.NET2.0 to retrieve the custom structure you have defined for your site.
o Login Controls. The new login controls provide the building blocks to
add authentication and authorization-based UI to your site, such as login
forms, create user forms, password retrieval, and custom UI for logged inusers or roles. These controls use the built-in membership and role
services in ASP.NET 2.0 to interact with the user and role information
defined for your site.
o Web Part Controls. Web parts are an exciting new family of controls that
enable you to add rich, personalized content and layout to your site, aswell as the ability to edit that content and layout directly from your
1
7/30/2019 asp.net eamples
2/21
ASP.NET 2.0 Tutorial
application pages. These controls rely on the personalization services in
ASP.NET 2.0 to provide a unique experience for each user in your
application.
Master Pages. This feature provides the ability to define common structure and
interface elements for your site, such as a page header, footer, or navigation bar,in a common location called a "master page", to be shared by many pages in your
site. In one simple place you can control the look, feel, and much of functionalityfor an entire Web site. This improves the maintainability of your site and avoids
unnecessary duplication of code for shared site structure or behavior.
Themes and Skins. The themes and skins features in ASP.NET 2.0 allow for
easy customization of your site's look-and-feel. You can define style information
in a common location called a "theme", and apply that style information globallyto pages or controls in your site. Like Master Pages, this improves the
maintainability of your site and avoid unnecessary duplication of code for shared
styles.
Personalization. Using the new personalization services in ASP.NET 2.0 you can
easily create customized experiences within Web applications. The Profile objectenables developers to easily build strongly-typed, sticky data stores for user
accounts and build highly customized, relationship based experiences. At the
same time, a developer can leverage Web Parts and the personalization service toenable Web site visitors to completely control the layout and behavior of the site,
with the knowledge that the site is completely customized for them.
Personalizaton scenarios are now easier to build than ever before and requiresignificantly less code and effort to implement.
Localization. Enabling globalization and localization in Web sites today isdifficult, requiring large amounts of custom code and resources. ASP.NET 2.0
and Visual Studio 2005 provide tools and infrastructure to easily build
Localizable sites including the ability to auto-detect incoming locale's and displaythe appropriate locale based UI. Visual Studio 2005 includes built-in tools to
dynamically generate resource files and localization references. Together,
building localized applications becomes a simple and integrated part of thedevelopment experience.
Administration and Management
ASP.NET 2.0 is designed with administration and manageability in mind. We recognizethat while simplifying the development experience is important, deployment and
maintenance in a production environment is also a key component of an application's
lifetime. ASP.NET 2.0 introduces several new features that further enhance thedeployment, management, and operations of ASP.NET servers.
2
7/30/2019 asp.net eamples
3/21
ASP.NET 2.0 Tutorial
Configuration API. ASP.NET 2.0 contains new configuration management
APIs, enabling users to programmatically build programs or scripts that create,
read, and update Web.config and machine.config configuration files.
ASP.NET MMC Admin Tool. ASP.NET 2.0 provides a new comprehensive
admin tool that plugs into the existing IIS Administration MMC, enabling anadministrator to graphically read or change common settings within our XML
configuration files.
Pre-compilation Tool. ASP.NET 2.0 delivers a new application deployment
utility that enables both developers and administrators to precompile a dynamicASP.NET application prior to deployment. This precompilation automatically
identifies any compilation issues anywhere within the site, as well as enables
ASP.NET applications to be deployed without any source being stored on theserver (one can optionally remove the content of .aspx files as part of the compile
phase), further protecting your intellectual property.
Health Monitoring and Tracing. ASP.NET 2.0 also provides new health-monitoring support to enable administrators to be automatically notified when an
application on a server starts to experience problems. New tracing features willenable administrators to capture run-time and request data from a production
server to better diagnose issues. ASP.NET 2.0 is delivering features that will
enable developers and administrators to simplify the day-to-day management andmaintenance of their Web applications.
Flexible Extensibility
ASP.NET 2.0 is a well-factored and open system, where any component can be easily
replaced with a custom implementation. Whether it is server controls, page handlers,compilation, or core application services, you'll find that all are easily customizable andreplaceable to tailor to your needs. Developers can plug in custom code anywhere in the
page lifecycle to further customize ASP.NET 2.0 to their needs.
Provider-driven Application Services. ASP.NET 2.0 now includes built-in
support for membership (user name/password credential storage) and rolemanagement services out of the box. The new personalization service enables
quick storage/retrieval of user settings and preferences, facilitating rich
customization with minimal code. The new site navigation system enables
developers to quickly build link structures consistently across a site. As all of
these services are provider-driven, they can be easily swapped out and replacedwith your own custom implementation. With this extensibility option, you have
complete control over the data store and schema that drives these rich applicationservices.
Server Control Extensibility. ASP.NET 2.0 includes improved support for
control extensibility, such as more base classes that encapsulate common
behaviors, improved designer support, more APIs for interacting with client-side
3
7/30/2019 asp.net eamples
4/21
ASP.NET 2.0 Tutorial
script, metadata-driven support for new features like themes and accessibility
verification, better state management, and more.
Data Source Controls. Data access in ASP.NET 2.0 is now performed
declaratively using data source controls on a page. In this model, support for new
data backend storage providers can be easily added by implementing custom datasource controls. Additionally, the SqlDataSource control that ships in the box has
built-in support for any ADO.NET managed provider that implements the newprovider factory model in ADO.NET.
Compilation Build Providers. Dynamic compilation in ASP.NET 2.0 is nowhandled by extensible compilation build providers, which associate a particular
file extension with a handler that knows how to compile that extension
dynamically at runtime. For example, .resx files can be dynamically compiled toresources, .wsdl files to web service proxies, and .xsd files to typed DataSet
objects. In addition to the built-in support, it is easy to add support for additional
extensions by implementing a custom build provider and registering it inWeb.config.
Expression Builders. ASP.NET 2.0 introduces a declarative new syntax forreferencing code to substitute values into the page, called Expression Builders.
ASP.NET 2.0 includes expression builders for referencing string resources for
localization, connection strings, application settings, and profile values. You canalso write your own expression builders to create your own custom syntax to
substitute values in a page rendering.
Performance and Scalability
ASP.NET is built to perform, using a compiled execution model for handling pagerequests and running on the world's fastest web server, Internet Information Services.ASP.NET 2.0 also introduces key performance benefits over previous versions.
64-Bit Support. ASP.NET 2.0 is now 64-bit enabled, meaning it can take
advantage of the full memory address space of new 64-bit processors and servers.
Developers can simply copy existing 32-bit ASP.NET applications onto a 64-bitASP.NET 2.0 server and have them automatically be JIT compiled and executed
as native 64-bit applications (no source code changes or manual re-compile are
required).
Caching Improvements. ASP.NET 2.0 also now includes automatic databaseserver cache invalidation. This powerful and easy-to-use feature allowsdevelopers to aggressively output cache database-driven page and partial page
content within a site and have ASP.NET automatically invalidate these cache
entries and refresh the content whenever the back-end database changes.Developers can now safely cache time-critical content for long periods without
worrying about serving visitors stale data.
4
7/30/2019 asp.net eamples
5/21
ASP.NET 2.0 Tutorial
The remainder of the QuickStart presents practical examples of these and other features
in ASP.NET.
5
7/30/2019 asp.net eamples
6/21
ASP.NET 2.0 Tutorial
Introduction to Visual Web Developer 2005 Express
Edition
Visual Web Developer 2005 Express Edition is part of the Microsoft Visual Studio 2005family, and is the best development tool for building data driven web applications with
ASP.NET 2.0. As part of the Express family, Visual Web Developer provides a seamless
upgrade path to Visual Studio Standard, Professional, and Team System.
Visual Web Developer is tuned to the specific needs of the Web developer through a newWeb profile that exposes a menu and window layout optimized for Web development.
The environment includes a best-of-breed HTML source editor, an improved visual page
designer, a new project system, better support for working with data, and full XHTMLstandards support. Collectively, these features enable you to develop data-driven Web
applications faster and easier than ever before. Below we'll dive in and explore a few of
the many Web development improvements coming with Visual Web Developer.
Better Source Code Editing
Visual Web Developer has an improved HTML source editor which enables you to write
and modify your pages faster. The source editor provides full Intellisense throughout
your files and has new features for navigating and validating your markup.
Intellisense Everywhere
Intellisense -- the popup code hints which appear while you type -- has a dramatic impacton your productivity as a developer. While support for Intellisense in Visual Studio .NET2003 is excellent today, support for Intellisense in Visual Web Developer gets even
better.
In Visual Web Developer, Intellisense pops up everywhere. For example, you can take
full advantage of Intellisense within the script blocks in single file ASP.NET pages. Inaddition, Visual Web Developer also supports Intellisense for ASP.NET Page Directives
and for inline CSS style attributes within a page.
Visual Web Developer also provides Intellisense for all sections within a Web.Config
configuration file, as well as any generic XML file that contains a DTD or XML Schemareference.
Using Intellisense in a single file ASP.NET page
HTML Source Preservation
6
7/30/2019 asp.net eamples
7/21
ASP.NET 2.0 Tutorial
Visual Web Developer respects your HTML. The formatting of your HTML markup --
including all white space, casing, indention, carriage returns, and word wrapping -- is
now preserved exactly as originally written, even when switching back and forth betweenthe design view and source view of the page. You can completely trust Visual Web
Developer to never modify your markup.
HTML Formatting Options
Visual Web Developer enables you to precisely control the format of all HTML and
ASP.NET Server Control markup generated using the WYSIWYG designer. You cannow configure the tag casing, attribute quotation, indention style and word wrap
characteristics of every html or server control tag in a page. You can set these formatting
options as defaults for all markup, as well as optionally override each formatting optionon a per tag/control basis. This provides you with the flexibility to fully control exactly
how you want your markup to be generated.
HTML format settings can be exported and imported from Visual Web Developer toenable markup style standardization across multiple developers on a team. Visual WebDeveloper also enables developers to easily apply HTML formatting rules to existing
markup source (to handle those cases when you need to update existing HTML source
with new formatting rules).
Tag Navigator
The HTML source editor within Visual Web Developer ships with a new ?Tag Navigator?feature that enables developers to easily track their location and navigate within a
complicated HTML document. The Tag Navigator displays the current "path" within the
source of an HTML page by displaying a list of all the HTML tags which contain the tagwhere your cursor is currently located. Clicking on any of the nodes enables developers
to optionally change the source level selection, and quickly move up and down a deepHTML hierarchy.
Imagine, for example, that you are editing the source of an HTML page with multiple
nested HTML tables. Editing nested tables can be challenging since it is easy to get lost
within the jumble of nested table rows and cells. However, by taking advantage of theTag Navigator, you can avoid getting lost since the Tag Navigator continuously displays
your current path within the hierarchy of table elements.
Tag Outlining
Tag Outlining enables you to work more effectively with large HTML documents. With
Tag Outlining, you can right-click any HTML tag in the source editor and select Collapse
Tag to hide the entire contents of the tag. Collapsing different regions of the HTMLsource code contained in a page makes it easier to focus on the particular region of the
page which you need to edit.
7
7/30/2019 asp.net eamples
8/21
ASP.NET 2.0 Tutorial
Flexible Browser Targeting and Validation
Visual Web Developer enables you to easily target a specific HTML standard or browser
when writing your HTML pages. For example, you can target your HTML pages to work
with a particular browser such as Netscape Navigator 4.0 or Internet Explorer 6.0.
Alternatively, you can target a particular HTML standard such as XHTML 1.0 Strict orXHTML 1.0 Transitional.
Your HTML will then be validated in real-time as you type in the source editor. Invalid
HTML will automatically be underlined with a red squiggly (with a tooltip displaying anexplanation of precisely how you violated the target). These validation errors are also
summarized in real-time within the ?Task List?window.
All browser/standard validation rules are pluggable within Visual Web Developer, and
can be easily extended and customized by developers. Visual Web Developer will
include a number of automatic validation targets out of the box ?including built-in
validation support for XHTML, XHTML Transitional, and all major desktop and mobilebrowsers.
Selecting a validation target
Code Refactoring
Code Refactoring enables you to easily and systematically make changes to your code.
Code Refactoring is supported everywhere that you can write code including both code-
behind and single-file ASP.NET pages. For example, you can use Code Refactoring toautomatically promote a public field to a full property.
Intellitask
Intellitask is like a super smart clipboard designed for working with code. Intellitaskimproves your productivity by enabling you to easily apply standard code snippets
anywhere within the source editor. Simply by right-clicking, you can inject common code
into your pages. Visual Web Developer will ship with more than 200 web specific
Intellitask code snippets out of the box. Better yet, you can add your own code templatesto Intellitask so that you can quickly modify your code in the future.
Richer Visual Designer
Visual Web Developer has an improved designer which makes it easier to visually build
ASP.NET Web applications. By taking advantage of the new designer tools, you can
build a feature rich, database-driven Web application without writing a single line ofcode.
8
7/30/2019 asp.net eamples
9/21
ASP.NET 2.0 Tutorial
ASP.NET Master Page Designer
Master Pages enable you to create a common look and feel for the pages in an ASP.NET
Web application. You can take advantage of Master Pages to create a single page layout
and apply the page layout to multiple Content Pages. For example, you can use a Master
Page to ensure that every page in an application contains the same standard header,footer, and navigation bar.
Visual Web Developer provides full WYSWIYG authoring support for ASP.NET Master
Pages. After you create a Master Page, you can apply the Master to new ASP.NET Pageswithin your Web site. Visual Web Developer provides great editing support when
authoring an ASP.NET page based on a Master?enabling the designer to see what the
combined page will look like, while simultaneously ghosting out all content from the
Master that cannot be edited on the Content Page.
Master Pages in the designer
Smart Tasks
Visual Web Developer enables you to perform many of the most common programming
tasks directly from the designer surface. By taking advantage of Smart Tasks, You cancreate an entire, feature rich, database-driven Web application without writing a single
line of code.
When you drag new controls onto the designer surface, a popup list of common tasks
automatically appears. You can use the common tasks list to quickly configure a control'sproperties, as well as walk through common operations you might perform with it. For
example, when you add a GridView control to a page, a common task list appears which
enables you to quickly enable sorting, paging, or editing for the GridView. When youadd a TextBox control to a page, a common task list appears which enables you to
quickly associate a validation control with the control.
Enabling GridView options with Smart Tasks
Improved ASP.NET Template Editing
Visual Web Developer has better designer support for editing templates. You can take
advantage of the new template editing features when working with data controls such asthe DataList and GridView controls.
When adding a control to a template in the designer, you can easily specify the databound
expressions to associate with the control properties. For example, if you drag a TextBox
9
7/30/2019 asp.net eamples
10/21
ASP.NET 2.0 Tutorial
control onto a template, you can bind the TextBox control's Text property to a particular
field from the data control's data source. The Edit Databindings dialog box provided by
the Visual Web Developer template editing designer enables you to easily bind particularfields by name.
Improved Table Editing
Visual Web Developer has better HTML table editing features. The improved Insert
Table dialog box enables you to quickly control the look and feel of the new table when it
is added to the designer surface. In addition, Visual Web Developer provides the abilityto resize tables, table columns and table rows graphically within the designer surface (just
click and hold down the appropriate element to size it).
Better Web Projects
Visual Web Developer provides you with more flexibility and features for managing thefiles in your web projects. The new web project system includes new tools for accessing,
compiling, and publishing your Web application projects.
File System Support
Visual Web Developer provides you with the option of creating a new Web applicationwithin any folder on your computer. When you create a file system project, you do not
need to have IIS or Front Page Server Extensions installed on your computer. You can
simply point at a folder and start building Web pages.
Creating a File System Web site
Visual Web Developer includes its own built-in ASP.NET enabled Web server. This
enables you to develop and debug Web applications on a computer without IIS installed.
It also enables developers to build and debug web applications without requiringAdministrator access.
The built-in Web server provides you with a more secure way of building applications on
a development machine. The built-in Web server cannot be accessed remotely (it can
only be used by a local web browser) and it automatically shuts down when you close theVisual Web Developer development environment.
Local IIS Support (No FrontPage Server Extensions Required)
In addition to file system projects, Visual Web Developer now enables you to more easily
manage projects which work with an IIS Web server. When you create a new IIS project,
you can now view all of the Web sites and applications configured on your machine. You
10
7/30/2019 asp.net eamples
11/21
ASP.NET 2.0 Tutorial
can even create new IIS Web applications or virtual directories directly from the New
Web Site dialog box.
Frontpage Server Extensions (FPSE) are no longer required for locally developed IIS webapplications. You can create and fully manage your websites without having to install or
configure them.
FTP Support
Visual Web Developer now has built-in support for editing and updating remote web
projects using the standard File Transfer Protocol (FTP). You can quickly connect to a
remote Web site using FTP within the New Web Site and Open Web Site dialog box.
Better Web Publishing
With Visual Web Developer, you can now publish a Web site to a remote server easier
than ever before. Built-in publishing features enable developers to easily keep files in alocal project synchronized with files located on a remote Web server. Visual Web
Developer provides automatic logging support for all files copied, and enables developers
to quickly identify whether the latest files have been updated.
Publishing a Web site to a remote Web server
Pre-Compiled ASP.NET Web Sites
Visual Web Developer now includes built-in IDE support for pre-compiling ASP.NET2.0 applications. By taking advantage of pre-compilation, you can automatically validateand compile all code in a site (including code-behind, inline code and business classes)
and emit an output directory with only compiled .dll assemblies and the application's
web.config file (all HTML markup and .aspx files will optionally be removed). In
addition, you can choose to obfuscate the resulting code as part of the pre-compilationprocess for greater intellectual property protection.
The pre-compilation feature enables developers to easily build and re-sell ASP.NET web
applications without having to ship their source. It can also improve the site's
performance and startup time on a production server.
Better Data Support
Visual Web Developer makes it much easier to work with data in your Web applications.
Drag and Drop Data Access
11
7/30/2019 asp.net eamples
12/21
ASP.NET 2.0 Tutorial
You can easily create a database-driven Web page by dragging and dropping data
controls onto a page. By taking advantage of the new ASP.NET 2.0 data source controls,
you can easily connect to a database, retrieve database records, and update databaserecords without writing any code (or having Visual Studio write any code for you!).
Imagine, for example, that you want to display all the records from a Microsoft SQLServer database table named Products in a Web page. To do this, you simply need to drag
two controls onto the page: a SqlDataSource control and a GridView control. By setting afew properties of these controls, you can automatically retrieve and display the records in
a Web page.
Data Access Layer Designer
Visual Web Developer provides built-in designer support for building and maintaining a
Data Access Layer within your web application. The data designer enables developers tomodel database tables and stored procedures as components that encapsulate procedural
ADO.NET data access logic. You can then easily access and update your data from bothweb pages and business objects through these data components.
Powerful Object Data Binding
Visual Web Developer enables you to quickly create 3-tier applications with distinct
presentation, business, and data layers. By taking advantage of the new ASP.NETObjectDataSource control, you can declaratively bind data controls -- like the GridView,
DataList, and DropDownList controls -- to a business or data component instead of
binding the controls directly to a database. This enables clean encapsulation andabstraction of functionality within your application ?and eliminates the need to write any
data access code in your presentation layer.
The development environment automatically guides developers through the process of
binding a data control to a business object. Developers are prompted to select the
particular methods from the business object to use for selecting, inserting, updating, anddeleting data. No code is required from the page developer.
Connection String Management
Visual Web Developer helps you avoid hard-coding database connection strings into yourASP.NET pages. All data connection dialogs and wizards provide you with the option of
storing database connection strings in an application's Web.Config file.
Storing database connection strings in the Web.Config file makes your connection strings
more manageable and more secure. If you need to change your database password, youneed to change it at only one location. The ASP.NET 2.0 MMC Admin tool
automatically provides administrators with an easy to use interface for changing
connection strings on servers. In addition, the tool can be used to encrypt connectionstrings on production servers.
12
7/30/2019 asp.net eamples
13/21
ASP.NET 2.0 Tutorial
Better Standards Support
Visual Web Developer enables you to easily build applications that conform to industry
and government standards. The development environment includes new tools for
supporting W3C standards such as XHTML and government standards such asaccessibility standards.
XHTML Compliant Designer
All HTML code generated by Visual Web Developer is XHTML compliant. For
example, all the formatting options available from the toolbar generate HTML which is
fully XHTML compliant. All tags generated by the designer are well-formed andproperly cased for XHTML.
In addition to XHTML designer support, Visual Web Developer also includes tools for
helping you write XHTML compliant code in the source editor. While working in the
source editor, you can validate your HTML source code against either the XHTML 1.0Transitional or XHTML 1.0 Strict standards. When your code doesn't successfully
validate, you are provided with an explanation for the validation failure.
Accessibility Checker
Creating accessible Web pages -- Web pages which can be used by persons with
disabilities -- is a requirement for many government agencies and large corporations.Visual Web Developer now enables you to easily validate and enforce accessibility
standards.
You can use the integrated Visual Web Developer Accessibility Checker(available in
Visual Studio Standard Edition and above only) to quickly identify accessibility problemsin your application. The Accessibility Checker validates your ASP.NET pages against
both the Section 508 and W3C Web Content Accessibility Guidelines (WCAG)
standards, and will automatically output warnings and errors to the IDE Task List.
Summary
Visual Web Developer is the best development tool for building dynamic, data drivenweb applications with ASP.NET 2.0. As detailed above, and demonstrated in the
Quickstarts, it provides it provides major enhancements for the Web application
developer. With Visual Web Developer and the ASP.NET enhancements you will be able
to build feature rich, database-driven Web applications faster and easier than ever before.
13
7/30/2019 asp.net eamples
14/21
ASP.NET 2.0 Tutorial
Building a Web Application
What's New in 2.0
Dynamically Compiled Classes - In addition to placing pre-compiled classes in
the Bin directory, ASP.NET 2.0 now allows you to place shared class file sources
in the App_Code directory, where they will be dynamically compiled just likeASPX pages.
Simplified Code Behind Pages - Code-behind files in ASP.NET 2.0 use a new
language feature called partial classes, which allow code-behind files to bedynamically compiled with their associated ASPX pages into a single class type.
This means you no longer need to declare member variables in the code-behind
page for each control, which greatly simplifies maintenance of sites that use thiscode-separation technique.
Several New Server Controls - ASP.NET 2.0 include over 50 new controls,
making it easier than ever to create common UI elements in your web pages. For
example, the Data controls simplify data access scenarios, the Login controls addsecurity to your site, the Navigation controls enable site navigation, and WebPart
controls allow you to easily create personalized web pages.
New Declarative Expression Syntax - The declarative expression syntax inASP.NET 2.0 allows you to substitute application settings, connection strings, and
localization resources into your pages before they are parsed and executed.
This section discusses these and other features of basic ASP.NET applications.
A web application in ASP.NET is a collection of pages, controls, code modules, and
services all running under a single web server application directory (usually IIS).
ASP.NET makes it really easy to build the types of dynamic web applications that exist
everywhere on the Internet today. It provides a simple programming model based on
the .NET Framework and several built-in controls and services that enable many of thecommon scenarios found in most applications, with very little effort or code. In this
section we demonstrate the basic elements of a web application that we will usethroughout the remainder of Quickstart tutorial, including:
The ASP.NET Page Framework (Web Forms)
Web and HTML Server Controls
Shared Code Modules or Assemblies
14
7/30/2019 asp.net eamples
15/21
ASP.NET 2.0 Tutorial
This section also discusses a few improvements made to these application building blocks
in ASP.NET 2.0 over previous versions of ASP.NET.
15
7/30/2019 asp.net eamples
16/21
ASP.NET 2.0 Tutorial
Introduction to ASP.NET Pages
The ASP.NET Web Forms page framework is a scalable common language runtime
programming model that can be used on the server to dynamically generate Web pages.
Intended as a logical evolution of ASP (ASP.NET provides syntax compatibility withexisting pages), the ASP.NET page framework has been specifically designed to address
a number of key deficiencies in the previous model. In particular, it provides the ability to
create and use reusable UI controls that can encapsulate common functionality and thusreduce the amount of code that a page developer has to write, the ability for developers to
cleanly structure their page logic in an orderly fashion (not "spaghetti code"), and the
ability for development tools to provide strong WYSIWYG design support for pages(existing classic ASP code is opaque to tools). This section of the QuickStart provides a
high-level code walkthrough of some basic ASP.NET page features. Subsequent sections
of the QuickStart drill down into more specific details.
Writing Your First ASP.NET Page
ASP.NET pages are text files with an .aspx file name extension. Pages consist of codeand markup and are dynamically compiled and executed on the server to produce a
rendering to the requesting client browser (or device). They can be deployed throughout
an IIS virtual root directory tree. When a browser client requests .aspx resources, the
ASP.NET runtime parses and compiles the target file into a .NET Framework class. Thisclass can then be used to dynamically process incoming requests. (Note that the .aspx file
is compiled only the first time it is accessed; the compiled type instance is then reused
across multiple requests).
An ASP.NET page can be created simply by taking an existing HTML file and changingits file name extension to .aspx (no modification of code is required). For example, thefollowing sample demonstrates a simple HTML page that collects a user's name and
category preference and then performs a form postback to the originating page when a
button is clicked:
VB Intro1.aspx
Important: Note that nothing happens yet when you click the Lookup button. This isbecause the .aspx file contains only static HTML (no dynamic content). Thus, the same
HTML is sent back to the client on each trip to the page, which results in a loss of thecontents of the form fields (the text box and drop-down list) between requests.
Adding Simple Code to a Page
16
http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/pages/intro/intro1.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro1_vb.aspx7/30/2019 asp.net eamples
17/21
ASP.NET 2.0 Tutorial
ASP.NET provides syntax compatibility with existing ASP pages. This includes support
for code render blocks that can be intermixed with HTML content within an
.aspx file. These code blocks execute in a top-down manner at page render time.
The below example demonstrates how render blocks can be used to loop over an
HTML block (increasing the font size each time):
VB Intro2.aspx
Important: Unlike with ASP, the code used within the above blocks is actuallycompiled--not interpreted using a script engine. This results in improved runtime
execution performance.
ASP.NET page developers can utilize code blocks to dynamically modify HTML
output much as they can today with ASP. For example, the following sampledemonstrates how code blocks can be used to interpret results posted back from a
client.
VB Intro3.aspx
Important: While code blocks provide a powerful way to custom manipulate the
text output returned from an ASP.NET page, they do not provide a clean HTML
programming model. As the sample above illustrates, developers using only codeblocks must custom manage page state between round trips and custom interpret posted
values.
Introduction to ASP.NET Server Controls
In addition to code and markup, ASP.NET pages can contain server controls, which areprogrammable server-side objects that typically represent a UI element in the page, such
as a textbox or image. Server controls participate in the execution of the page and
produce their own markup rendering to the client. The principle advantage of server
controls is that they enable developers to get complex rendering and behaviors from
simple building-block components, dramatically reducing the amount of code it takes toproduce a dynamic Web page. Another advantage of server controls is that it is easy to
customize their rendering or behavior. Server controls expose properties that can be seteither declaratively (on the tag) or programmatically (in code). Server controls (and the
page itself) also expose events that developers can handle to perform specific actions
during the page execution or in response to a client-side action that posts the page back tothe server (a "postback"). Server controls also simplify the problem of retaining state
across round-trips to the server, automatically retaining their values across successive
17
http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/pages/intro/intro3.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro3_vb.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/pages/intro/intro2.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro2_vb.aspx7/30/2019 asp.net eamples
18/21
ASP.NET 2.0 Tutorial
postbacks.
Server controls are declared within an .aspx file using custom tags or intrinsic HTMLtags that contain a runat="server" attribute value. Intrinsic HTML tags are handled by
one of the controls in the System.Web.UI.HtmlControls namespace. Any tag that
doesn't explicitly map to one of the controls is assigned the type ofSystem.Web.UI.HtmlControls.HtmlGenericControl .
The following sample uses four server controls: , , , and .
At run time these server controls automatically generate HTML content.
VB Intro4.aspx
Important: Note that these server controls automatically maintain any client-enteredvalues between round trips to the server. This control state is not stored on the server (it is
instead stored within an form field that is round-trippedbetween requests). Note also that no client-side script is required.
In addition to supporting standard HTML input controls, ASP.NET enables developers toutilize richer custom controls on their pages. For example, the following sample
demonstrates how the control can be used to dynamically display
rotating ads on a page.
VB Intro5.aspx
Important: A detailed listing of all built-in server controls can be found in the Control
Reference section of this QuickStart.
Handling Server Control Events
Each ASP.NET server control is capable of exposing an object model containing
properties, methods, and events. ASP.NET developers can use this object model to
cleanly modify and interact with the page.
The following example demonstrates how an ASP.NET page developer can handle the
OnClickevent from the control to manipulate the Textproperty of the control.
18
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/default.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/default.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/pages/intro/intro5.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro5_vb.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/pages/intro/intro4.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro4_vb.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/default.aspxhttp://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/standard/default.aspx7/30/2019 asp.net eamples
19/21
ASP.NET 2.0 Tutorial
VB Intro6.aspx
This simple sample is functionally equivalent to the "Intro3" sample demonstrated earlier
in this section. Note, however, how much cleaner and easier the code is in this new
server-control-based version. As we will see later in the tutorial, the ASP.NET pageFramework also exposes a variety of page-level events that you can handle to write code
to execute a specific time during the processing of the page. Examples of these events are
Page_Load and Page_Render.
19
http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/pages/intro/intro6.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/pages/intro/intro6_vb.aspx7/30/2019 asp.net eamples
20/21
ASP.NET 2.0 Tutorial
Code Behind vs. Code Inline
ASP.NET provides two ways that you can organize code within your pages.
Inline Code Separation
The example below demonstrates a simple ASP.NET page with three server controls, a
TextBox, Button, and a Label. Initially these controls just render their HTML formequivalents. However, when a value is typed in the TextBox and the Button is clicked on
the client, the page posts back to the server and the page handles this click event in the
code of the page, dynamically updating the Text property of the Label control. The page
then re-renders to reflect the updated text. This simple example demonstrates the basicmechanics behind the server control model that has made ASP.NET one of the easiest
Web programming models to learn and master.
VB Inline Code Separation
Note that in the preceding example the event handler for the Button was located between tags in the same page containing the server controls. ASP.NET
calls this type of page programming code-inline, and it is very useful when you want to
maintain your code and presentation logic in a single file. However, ASP.NET alsosupports another way to factor your code and presentation content, called the code-
behind model. When using code-behind, the code for handling events is located in a
physically separate file from the page that contains server controls and markup. This clear
delineation between code and content is useful when you need to maintain theseseparately, such as when more than one person is involved in creating the application. It
is often common in group projects to have designers working on the UI portions of anapplication while developers work on the behavior or code. The code-behind model is
well-suited to that environment.
Simplified Code Behind Model New in 2.0
ASP.NET 2.0 introduces an improved runtime for code-behind pages that simplifies the
connections between the page and code. In this new code-behind model, the page is
declared as a partial class, which enables both the page and code files to be compiled into
a single class at runtime. The page code refers to the code-behind file in the CodeFileattribute of the directive, specifying the class name in the Inherits
attribute. Note that members of the code behind class must be either public or protected(they cannot be private).
VB CodeBehind Code Separation
20
http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/simple/CodeBehind.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/simple/CodeBehind_vb.aspxhttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/simple/Inline.srchttp://quickstarts.asp.net/QuickStartv20/aspnet/samples/simple/Inline_vb.aspx7/30/2019 asp.net eamples
21/21
ASP.NET 2.0 Tutorial
The advantage of the simplified code-behind model over previous versions is that you do
not need to maintain separate declarations of server control variables in the code-behindclass. Using partial classes (new in 2.0) allows the server control IDs of the ASPX page
to be accessed directly in the code-behind file. This greatly simplifies the maintenance of
code-behind page
Top Related