SlideShare a Scribd company logo
Walkthrough: Creating a Basic
Web Forms Page in Visual
Studio
Other Versions
This walkthrough provides you with an introduction to the Web development environment in Visual
Studio and in Visual Web Developer Express for ASP.NET Web Forms pages. This walkthrough guides you
through creating a simple ASP.NET Web Forms page and illustrates the basic techniques of creating a new
page, adding controls, and writing code.
Note
This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create
using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages.
Tasks illustrated in this walkthrough include:
 Creating a file system Web site project.
 Familiarizing yourself with Visual Studio.
 Creating a single-file ASP.NET Web Forms page.
 Adding controls.
 Adding event handlers.
 Running pages by using the Web server that is built into Visual Studio for testing.
Prerequisites
In order to complete this walkthrough, you will need:
 Visual Studio or Visual Web Developer Express. For download information, see the Visual Studio
Development Center Web site.
Note
If you are using Visual Studio, this walkthrough assumes that you selected the Web
Developmentcollection of settings the first time that you started Visual Studio. For more
information, see How to: Select Web Development Environment Settings.
 The .NET Framework, which is installed when you install Visual Studio or Visual Web Developer
Express.
Creating a Web Site Project and a Web Forms Page
In this part of the walkthrough, you will create a Web site project and add a new page to it. You will also
add HTML text and run the page in your Web browser.
For this walkthrough, you will create a file system Web site project that does not require that you work
with Microsoft Internet Information Services (IIS). Instead, you will create and run your page in the local
file system.
A file system Web site project is one that stores pages and other files in a folder that you choose
somewhere on your computer. Other Web project options include the following:
 A local IIS Web site project, which stores your files in a subfolder of the local IIS root (typically,
inetpubwwwroot).
 An FTP site project, which stores files on a remote server that you gain access to across the
Internet by using File Transfer Protocol (FTP).
 A remote IIS Web site project, which stores files on a remote server that you can access across a
local network.
 A Web application project, which is similar to a file system Web site project except you compile it
before deployment and deploy it as a dynamic link library (.dll) file. For more information about
the difference between Web site projects and Web application projects, see Web Application
Projects versus Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Studio or Microsoft Visual Web Developer Express.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears, as shown in the following illustration:
3. Under Installed Templates, click Visual Basic or C# and then select ASP.NET Web Site.
When you create a Web site project, you specify a template. Each template creates a Web project
that contains different files and folders. In this walkthrough, you are creating a Web site based on
the ASP.NET Web Sitetemplate, which creates files and folders that are typically used in ASP.NET
Web sites.
4. In the Web Location box, select File System, and then enter the name of the folder where you
want to keep the pages of your Web site.
For example, type the folder name C:BasicWebSite.
5. Click OK.
Visual Studio creates a Web project that includes prebuilt functionality for layout (a master page,
the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script
files), and for authentication (ASP.NET membership). When a new page is created, by default
Visual Studio displays the page in Source view, where you can see the page's HTML elements.
The following illustration shows what you would see in Source view if you created a new Web
page named FirstWebPage.aspx.
A Tour of the Visual Studio Web Development Environment
Before you proceed with working on the page, it is useful to familiarize yourself with the Visual Studio
development environment. The following illustration shows you the windows and tools that are available
in Visual Studio and Microsoft Visual Web Developer Express.
Note
This diagram shows default windows and window locations. The View menu allows you to
display additional windows, and to rearrange and resize windows to suit your preferences. If
changes have already been made to the window arrangement, what you see will not match the
illustration.
The Visual Studio environment
To familiarize yourself with the Web designer
 Examine the preceding illustration and match the text to the following list, which describes the
most commonly used windows and tools. (Not all windows and tools that you see are listed here,
only those marked in the preceding illustration.)
o Toolbars. Provide commands for formatting text, finding text, and so on. Some toolbars
are available only when you are working in Design view.
o Solution Explorer window. Displays the files and folders in your Web site.
o Document window. Displays the documents you are working on in tabbed windows. You
can switch between documents by clicking tabs.
o Properties window. Allows you to change settings for the page, HTML elements, controls,
and other objects.
o View tabs. Present you with different views of the same document. Design view is a near-
WYSIWYG editing surface. Source view is the HTML editor for the page. Split view
displays both the Designview and the Source view for the document. You will work with
the Design and Source views later in this walkthrough. If you prefer to open Web pages
in Design view, on the Tools menu, click Options, select the HTML Designer node, and
change the Start Pages In option.
o ToolBox. Provides controls and HTML elements that you can drag onto your
page. Toolboxelements are grouped by common function.
o Server Explorer/Database Explorer. Displays database connections. If Server
Explorer is not visible, on the View menu, click Server Explorer or Database Explorer.
Note
The Server Explorer window is named Database Explorer in Microsoft Visual
Web Developer Express. To see all available menu items in Microsoft Visual
Web Developer Express, on the Toolsmenu, click Settings, and then click Expert
Settings.
Creating a New ASP.NET Web Forms Page
When you create a new Web site using the ASP.NET Web Site project template, Visual Studio adds an
ASP.NET Web Forms page named Default.aspx. You can use the Default.aspx page as the home page for
your Web site. However, for this walkthrough, you will create and work with a new page.
To add a page to the Web site
1. Close the Default.aspx page. To do this, right-click the tab that displays the file name and then
click Close.
2. In Solution Explorer, right-click the Web site (for example, C:BasicWebSite), and then click Add
New Item.
The Add New Item dialog box is displayed. The following illustration shows an example of
the Add New Item dialog box.
3. In the template list, select Web Form.
4. In the Name box, type FirstWebPage.
When you created the Web site project, you specified a default language based on the project
template that you selected. However, each time you create a new page or component for your
Web site, you can select the programming language for that page or component. You can use
different programming languages in the same Web site.
5. Clear the Place code in separate file check box.
In this walkthrough, you are creating a single-file Web Forms page with the code and HTML in the
same page. The code for ASP.NET Web Forms pages can be located either in the page or in a
separate class file.
6. Click Add.
Visual Studio creates the new page and opens it.
Adding HTML to the Web Forms Page
In this part of the walkthrough, you will add some static text to the page.
To add text to the page
1. At the bottom of the document window, click the Design tab to switch to Design view.
Design view displays the page that you are working on in a WYSIWYG-like way. At this point, you
do not have any text or controls on the page, so the page is blank except for a dashed line that
outlines a rectangle. This rectangle represents a div element on the page.
2. Click inside the rectangle that is outlined by a dashed line.
3. Type Welcome to Visual Web Developer and press ENTER twice.
The following illustration shows the text you typed in Design view.
4. Switch to Source view.
You can see the HTML that you created by typing in Design view, as shown in the following
illustration.
Running the Page
Before you proceed with adding controls to the page, you can try running it. To run a page, you need a
Web server. In a production Web site, you use IIS as your Web server. However, to test a page, you can
use the Visual Studio Development Server, which runs locally and does not require IIS. For file system Web
site projects, the default Web server in Visual Studio and Microsoft Visual Web Developer Express is the
Visual Studio Development Server.
To run the page
1. In Solution Explorer, right-click FirstWebPage.aspx and select Set as Start Page.
2. Press CTRL+F5 to run the page.
Visual Studio starts the Visual Studio Development Server. An icon appears in the Windows
taskbar to indicate that the Visual Studio Development Server is running, as shown in the
following illustration.
The page is displayed in the browser. Although the page you created has a file-name extension of
.aspx, it currently runs like any HTML page.
To display a page in the browser you can also right-click the page in Solution Explorer and
select View in Browser.
3. Close the browser.
Adding and Programming Controls
You will now add server controls to the page. Server controls, which include buttons, labels, text boxes,
and other familiar controls, provide typical form-processing capabilities for your ASP.NET Web Forms
pages. However, you can program the controls with code that runs on the server, not the client.
You will add a Button control, a TextBox control, and a Label control to the page and write code to handle
the Clickevent for the Button control.
To add controls to the page
1. Click the Design tab to switch to Design view.
2. Put the insertion point at the end of the Welcome to Visual Web Developer text and press
ENTER five or more times to make some room in the div element box.
3. In the Toolbox, expand the Standard group.
4. Drag a TextBox control onto the page and drop it in the middle of the div element box that
has Welcome to Visual Web Developer in the first line.
5. Drag a Button control onto the page and drop it to the right of the TextBox control.
6. Drag a Label control onto the page and drop it on a separate line below the Button control.
7. Put the insertion point above the TextBox control, and then type Enter your name:.
This static HTML text is the caption for the TextBox control. You can mix static HTML and server
controls on the same page. The following illustration shows how the three controls appear
in Design view.
Setting Control Properties
Visual Studio offers you various ways to set the properties of controls on the page. In this part of the
walkthrough, you will set properties in both Design view and Source view.
To set control properties
1. Select the Button control, and then in the Properties window, set Text to Display Name. The text
you entered appears on the button in the designer, as shown in the following illustration.
Note
If the Properties window is not displayed, press F4 to display it.
2.
3. Switch to Source view.
Source view displays the HTML for the page, including the elements that Visual Studio has
created for the server controls. Controls are declared using HTML-like syntax, except that the tags
use the prefix asp: and include the attribute runat="server".
Control properties are declared as attributes. For example, when you set the Text property for
the Buttoncontrol, in step 1, you were actually setting the Text attribute in the control's markup.
Note that all the controls are inside a form element, which also has the attribute runat="server".
Therunat="server" attribute and the asp: prefix for control tags mark the controls so that they
are processed by ASP.NET on the server when the page runs. Code outside of <form
runat="server"> and <script runat="server"> elements is sent unchanged to the browser,
which is why the ASP.NET code must be inside an element whose opening tag contains
the runat="server" attribute.
4. Put the insertion point after asp:Label in the <asp:Label> tag, and then press SPACEBAR.
A drop-down list appears that displays the list of properties you can set for a Label control. This
feature, referred to as IntelliSense, helps you in Source view with the syntax of server controls,
HTML elements, and other items on the page. The following illustration shows the IntelliSense
drop-down list for the Labelcontrol.
5. Select ForeColor and then type an equal sign and a quotation mark (=").
IntelliSense displays a list of colors.
Note
You can display an IntelliSense drop-down list at any time by pressing CTRL+J.
6. Select a color for the Label control's text. Make sure you select a color that is dark enough to read
against a white background.
The ForeColor attribute is completed with the color that you have selected, including the closing
quotation mark.
Programming the Button Control
For this walkthrough, you will write code that reads the name that the user enters into the text box and
then displays the name in the Label control.
To add a default button event handler
1. Switch to Design view.
2. Double-click the Button control.
Visual Studio switches to Source view and creates a skeleton event handler for
the Button control's default event, the Click event.
Note
Double-clicking a control in Designview is just one of several ways you can create event
handlers.
3. Inside the handler, type Label1 followed by a period (.).
When you type the period after Label, Visual Studio displays a list of available members for
the Labelcontrol, as shown in the following illustration.
4. Finish the Click event handler for the button so that it reads as shown in the following code
example.
C#
VB
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = TextBox1.Text + ", welcome to Visual Studio!";
}
5. Scroll down to the <asp:Button> element. Note that the <asp:Button> element now has the
attributeonclick="Button1_Click".
This attribute binds the button's Click event to the handler method you coded in the previous
step.
Event handler methods can have any name; the name you see is the default name created by
Visual Studio. The important point is that the name used for the onclick attribute must match the
name of a method in the page.
Running the Page
You can now test the server controls on the page.
To run the page
1. Press CTRL+F5 to run the page in the browser.
The page again runs using the Visual Studio Development Server.
2. Enter a name into the text box and click the button.
The name you entered is displayed in the Label control. Note that when you click the button, the
page is posted to the Web server. ASP.NET then recreates the page, runs your code (in this case,
the Buttoncontrol's Click event handler runs), and then sends the new page to the browser. If you
watch the status bar in the browser, you can see that the page is making a round trip to the Web
server each time you click the button.
3. In the browser, view the source of the page you are running.
In the page source code, you see only ordinary HTML; you do not see the <asp:> elements that
you were working with in Source view. When the page runs, ASP.NET processes the server
controls and renders HTML elements to the page that perform the functions that represent the
control. For example, the <asp:Button>control is rendered as the
HTML <input type="submit"> element.
4. Close the browser.
Working with Additional Controls
In this part of the walkthrough, you will work with the Calendar control, which displays dates a month at a
time. TheCalendar control is a more complex control than the button, text box, and label you have been
working with and illustrates some further capabilities of server controls.
In this section, you will add a System.Web.UI.WebControls.Calendar control to the page and format it.
To add a Calendar control
1. In Visual Studio, switch to Design view.
2. From the Standard section of the Toolbox, drag a Calendar control onto the page and drop it
below the divelement that contains the other controls:
The calendar's smart tag panel is displayed. The panel displays commands that make it easy for
you to perform the most common tasks for the selected control. The following illustration shows
the Calendar control as rendered in Design view.
3. In the smart tag panel, choose Auto Format.
The Auto Format dialog box is displayed, which allows you to select a formatting scheme for the
calendar. The following illustration shows the Auto Format dialog box for the Calendar control.
4. From the Select a scheme list, select Simple and then click OK.
5. Switch to Source view.
You can see the <asp:Calendar> element. This element is much longer than the elements for the
simple controls you created earlier. It also includes subelements, such as <WeekEndDayStyle>,
which represent various formatting settings. The following illustration shows the Calendar control
in Source view. (The exact markup that you see in Source view might differ slightly from the
illustration.)
Programming the Calendar Control
In this section, you will program the Calendar control to display the currently selected date.
To program the Calendar control
1. In Design view, double-click the Calendar control.
A new event handler is created in Source view.
2. Finish the SelectionChanged event handler with the following highlighted code.
C#
VB
protected void Calendar1_SelectionChanged(object sender,
System.EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToLongDateString();
}
Running the Page
You can now test the calendar.
To run the page
1. Press CTRL+F5 to run the page in the browser.
2. Click a date in the calendar.
The date you clicked is displayed in the Label control.
3. In the browser, view the source code for the page.
Note that the Calendar control has been rendered to the page as a table, with each day as
a td element containing an a element.
4. Close the browser.
Visual Studio Templates for
Web Projects
.NET Framework 4.5
Visual Studio includes project templates to help you get started when you create a web project. You can
create web application projects or web site projects. By considering the most appropriate project type
before you begin, you can save time when you create, test, and deploy the web project.
Web Project Templates
From the File menu, you can select either New Project or New Web Site. The New Project dialog box
provides a list of web application templates. Use the web application project template to create web
applications that are compiled into an assembly and that provide rich options for deployment.
The New Web Site dialog box provides a list of web site templates. Use the Web Site project template
when you want to compile the source code dynamically. For more information about the differences
between web project types, see Web Application Projects versus Web Site Projects.
Note
You can install additional products by using the NuGet package manager. In some cases, these
products include additional templates for new projects. The lists in this topic show you only the
templates that are included by default with Visual Studio 2012.
Web Application Templates
Web application templates help you create a web project that is compiled into an assembly for
deployment. The following table lists templates that appear in the New Project dialog box under
the Web category after you select a language (Visual Basic or Visual C#).
Project Template More Information
ASP.NET Web
Forms
Application
Use this project template to create a web application that is based on
ASP.NET Web Forms pages and that includes the following functionality.
You can choose not to use any of these features when they are not required
for your application.
 A master page.
 A cascading style sheet.
 Login security that uses the ASP.NET membership system.
 Ajax scripting that uses jQuery.
 Navigation that uses a menu control.
By default, the ASP.NET Web Application project template includes the
following:
 Folders to contain membership pages, client script files, and
cascading style sheet files.
 A data folder (App_Data), which is granted permissions that allow
ASP.NET to read and write to it at run time.
 A master page (the Site.master file).
 Web pages named Default.aspx, Contact.aspx, and About.aspx.
These content pages are based on the default master.
 A global application class (Global.asax file).
 A Web.config file.
 A Packages.config file.
 For more information, see ASP.NET Web Application
Projects and Web Application Projects versus Web Site Projects in
Visual Studio.
ASP.NET MVC 3
Web Application
Use this project template to create web applications that use a model-view-
controller pattern, using the ASP.NET MVC 3 release. The MVC pattern
helps separate the different aspects of the application (input logic, business
logic, and UI logic), while providing a loose coupling between these
elements. In addition, this project template promotes test-driven
development (TDD).
For more information, see ASP.NET MVC Overview.
ASP.NET MVC 4
Web Application
Use this project template to create web applications that use a model-view-
controller pattern, using the ASP.NET MVC 4 release.
For more information, see ASP.NET MVC Overview.
ASP.NET Empty
Web Application
This template creates an ASP.NET web application that includes a
Web.config file, but no other files. Use this project template when you do
not require the functionality built into the standard template.
ASP.NET
Dynamic Data
Entities Web
Application
Use this project template to create a Dynamic Data web application that
uses the ADO.NET Entity Framework. This type of Dynamic Data web
application can target any relational database.
Dynamic Data automatically generates a functional web application for
viewing and editing data, based on the schema of the data. For more
information, see ASP.NET Dynamic Data Overview.
ASP.NET AJAX
Server Control
Use this project template to create a web server control for ASP.NET Web
Forms pages that incorporates Ajax functionality. The control consists of
server and client code that work together to produce rich client behavior.
For more information, see ASP.NET AJAX Overview.
ASP.NET AJAX
Server Control
Extender
Use this project template to create an Ajax component that enhances the
client capabilities of standard ASP.NET web server controls.
For more information, see ASP.NET AJAX Extender Controls Overview.
ASP.NET Server
Control
Use this project template to create a custom ASP.NET web server control
that can be used in ASP.NET Web Forms pages.
For more information, see Developing Custom ASP.NET Server Controls.
Web Site Templates
Web site templates help you create a web project that by default is compiled dynamically. The following
table lists templates that appear in the New Web Site dialog box.
Project
Template
More Information
ASP.NET Web
Forms Site
Use this project template to create a website that includes the following
functionality. You can choose not to use any of these features when they are
not required for your application.
 A master page.
 A cascading style sheet.
 Login security that uses the ASP.NET membership system.
 Ajax scripting that uses jQuery.
 Navigation using a menu control.
By default, the ASP.NET Web Site project template includes the following:
 Folders to contain membership pages, client script files, and
cascading style sheet files.
 A data folder (App_Data), which is granted permissions that allow
ASP.NET to read and write to it at run time.
 A master page (.master file).
 Web pages named Default.aspx and About.aspx. In the project
template, these pages are content pages that use default master page.
 A global application class (Global.asax file).
 A Web.config file.
For more information, see Walkthrough: Creating a Basic Web Page in
Visual Studio.
ASP.NET Web
Site (Razor v2)
Use this project template to create a website that uses ASP.NET Web Pages
version 2 with Razor syntax. For more information, see Introduction to
ASP.NET Web Programming Using the Razor Syntax.
ASP.NET Web
Site (Razor)
Use this project template to create a website that uses ASP.NET Web Pages
with the Razor syntax. For more information, see Introduction to ASP.NET
Web Programming Using the Razor Syntax.
ASP.NET Empty
Web Site
This template creates an ASP.NET website that includes a Web.config file
but no other files. Use this project template when you do not require the
functionality built into the standard.
ASP.NET
Dynamic Data
Entities Web Site
Use this project template to create a Dynamic Data website that uses the
ADO.NET Entity Framework. This type of Dynamic Data web application
can target any relational database.
Dynamic Data automatically generates a functional web application for
viewing and editing data, based on the schema of the data. For more
information, see ASP.NET Dynamic Data.
WCF Service Use this project template to create a Windows Communication Foundation
(WCF) service. You can extend the service so that a website, web
application, Silverlight application, Ajax application, or other client can call
it.
For more information, see Windows Communication Foundation.
ASP.NET
Reports Web Site
Use this project template to create an ASP.NET website that contains a
report (.rdlc file), a default ASP.NET Web Forms page (.aspx file) that
contains a ReportViewer control, and a Web.config file. For more
information, see Microsoft Reports.
Walkthrough: Creating a Basic
Web Forms Page with Code
Separation in Visual Studio
Other Versions
When you create ASP.NET Web Forms pages and write code in them, you can select from two models for
how to manage the visible elements (controls and text) and your programming code. In the single-file
model, the visible elements and code are kept together in the same file. In the alternative model, called
"code separation," the visible elements are in one file and the code is in another file, referred to as the
"code-behind" file. This walkthrough introduces you to Web Forms pages that use code separation.
Note
This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create
using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages.
The single-file model is introduced in Walkthrough: Creating a Basic Web Forms Page in Visual Studio.
The walkthrough you are reading now shows you how to create a Web page with the same functionality
as the page in the single-file walkthrough, but with a focus on using code separation.
The choice between using single-file pages and pages with code separation is primarily one of
convenience and personal preference. Working with both models in Microsoft Visual Studio is similar;
both models have approximately equal support in the editor. Both models have equivalent performance
when the page runs. The page with code separation makes it more practical to let a Web designer work
on the layout of a page while a programmer creates the code for the page, because the two pages can be
edited separately.
Tasks illustrated in this walkthrough include:
 Creating an ASP.NET Web Forms page with code separation.
 Adding server controls.
 Adding event handlers.
 Running pages with the Visual Studio Development Server.
Prerequisites
In order to complete this walkthrough, you will need:
 Visual Studio or Visual Web Developer Express.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
Creating a Web Site Project and Page
In this part of the walkthrough, you will create a Web site project and add a new page to it. You will also
add HTML text and run the page in your Web browser.
If you have already created a Web Forms Web site project in Visual Studio (for example, by following the
steps inWalkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and
skip to "Creating a New Page" later in this walkthrough. Otherwise, create a new Web site project and
page by following these steps.
To create a file system Web site project
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master
page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client
script files), and for authentication (ASP.NET membership).
Creating a New Web Forms Page
When you create a new Web site project, Visual Studio adds a Web Forms page named Default.aspx. By
default, Visual Studio creates a page with code separation.
To add a page with code separation to the Web site
1. Close the Default.aspx page. To do this, right-click the tab with the file name in it and then
click Close.
2. In Solution Explorer, right-click the Web site (for example, C:BasicWebSite) and then click Add
New Item.
3. Under Installed Templates, click Visual Basic or Visual C# and then select Web Form from the
list.
4. In the Name box, enter WebPageSeparated.
5. Make sure that the Place code in separate file check box is selected.
6. Make sure that the Select master page check box is cleared.
For this walkthrough, you will create a page that does not use the master page that is included in
the Web site project.
7. Click Add.
Visual Studio creates two files. The first file, WebPageSeparated.aspx, will contain the page's text
and controls, and is opened in the editor. A second file, WebPageSeparated.aspx.vb or
WebPageSeparated.aspx.cs (depending on what programming language you selected), is the
code file. You can see both files in Solution Explorer by clicking the plus sign (+) next to the
WebPageSeparated.aspx file; the code file has been created but is not open. You will open it later
in the walkthrough when you write code.
Adding HTML to the Web Forms Page
In this part of the walkthrough, you will add some static HTML text to the WebPageSeparated.aspx page.
To add text to the page
1. Click the Design tab at the bottom of the document window to switch to Design view.
Design view displays the page you are working on in a WYSIWYG-like way. At this point, you do
not have any text or controls on the page, so the page is blank.
2. Place the insertion pointer in the div element that is already on the page.
3. Type the words Welcome to Visual Studio Using Code Separation.
4. Switch to Source view.
You can see the HTML that you created by typing in Design view. At this stage, the page looks
like an ordinary HTML page. The only difference is in the <%@ Page %> directive at the top of the
page.
Adding and Programming Server Controls
In this part of the walkthrough, you will add server controls to the Web Forms page: a button, text box,
and label control. You will also write code to handle the button's Click event. Server controls, which
include buttons, labels, text boxes, and other familiar controls, provide typical form-processing capabilities
for your ASP.NET Web Forms pages. However, you can program the controls with code that runs on the
server, not the client.
To add controls to the page
1. Click the Design tab to switch to Design view.
2. Place the insertion pointer after the text that you added previously.
3. Press ENTER a few times to make some room.
4. From the Standard tab in the Toolbox, drag three controls onto the page: a TextBox control,
a Button control, and a Label control.
5. Put the insertion pointer in front of the text box and type Enter your name:.
This static HTML text is the caption for the TextBox control. You can mix static HTML and server
controls on the same page.
Setting Server Control Properties
Visual Studio offers you various ways to set the properties of server controls on the page. In this part of
the walkthrough, you will work with properties in both Design view and Source view.
To set control properties
1. Select the Button control and in the Properties window set its Text property to Display Name.
2. Switch to Source view.
Source view displays the HTML markup for the page, including the elements that Visual Studio
has created for the server controls. Server controls are declared using HTML-like syntax, except
that the tags use the prefix asp: and include the attribute runat="server".
Server control properties are declared as attributes. For example, when you set the
button's Text property in Step 1, you were actually setting the Text attribute in the control's
markup.
Note that all the controls are inside a form element that also has the attribute runat="server".
Therunat="server" attribute and the asp: prefix for control tags mark the controls so that they
are processed by ASP.NET when the page runs.
Programming the Button Control
For this walkthrough, you will write code that reads the name that the user enters in the text box and then
displays it in the Label control.
To add a default button event handler
1. Switch to Design view
2. Double-click the Button control.
Visual Studio opens the WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs file in a
separate window in the editor. The file contains a skeleton Click event handler for the button.
3. Complete the Click event handler by adding the following highlighted code.
C#
VB
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = TextBox1.Text + ", welcome to Visual Studio!";
}
Notice that as you type, IntelliSense helps you with context-sensitive choices. This is identical to
the behavior when you are coding in a single-file page.
Examining the Page and Code File
You now have two files that make up the complete Web Forms page named WebPageSeparated:
WebPageSeparated.aspx and WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs. In this section of
the walkthrough, you will examine how these files are structured and how they relate to each other.
To examine the page and code file
1. Click the WebPageSeparated.aspx tab at the top of the editor window to switch to the page file.
2. Switch to Source view.
At the top of the page is an @ Page directive that binds this page to the code file. The directive
looks like the following code.
C#
VB
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="WebPageSeparated.aspx.cs" Inherits="WebPageSeparated" %>
(The line does not wrap in the editor, and the language attribute and file name extensions will
match the programming language you selected.)
When the page runs, ASP.NET dynamically creates an instance of a class representing the Web
Forms page. The Inherits attribute identifies the class defined in the code-behind file from which
the .aspx page is derived. By default, Visual Studio uses the page name as the basis for the class
name in the code-behind file.
The CodeFile attribute identifies the code file for this page. In simple terms, the code-behind file
contains the event-handling code for your page.
3. Click the WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs tab to switch to the code
file.
The code file contains code that is similar to a class definition. However, it is not a complete class
definition; instead, it is a partial class that contains only a portion of the complete class that will
make up the page. Specifically, the partial class defined in the code file contains the event
handlers and other custom code that you write. At run time, ASP.NET generates another partial
class containing your user code. This complete class is then used as the base class that is used to
render the page. For more information, see ASP.NET Page Class Overview.
Running the Page
You can now test the page.
To run the page
1. Press CTRL+F5 to run the page in the browser.
The page runs using the Visual Studio Development Server.
2. Enter a name in the text box and click the button.
The name you entered is displayed in the Label control.
3. In the browser, view the source of the page you are running.
4. Close the browser.
The page works exactly the same as it would if it were a single-file page. (If you followed the steps
inWalkthrough: Creating a Basic Web Forms Page in Visual Studio to create a single-file page, you
can compare the two pages to see that they are the same when running.)
Next Steps
This walkthrough has illustrated how to create and edit a Web Forms page that uses code separation.
From the perspective of creating and running the page, there is not a significant difference between a
single-file page and a page with code separation.
You might want to explore other features. For example, you might want to:
 Create different types of Web sites. In addition to creating a file-system Web site as you did in
this walkthrough, you can work with Web site projects using Microsoft Internet Information
Services (IIS), and FTP, and you can work with Web application projects. For details, see Types of
Web Site Projects in Visual Studioand Web Application Projects versus Web Site Projects in Visual
Studio.
 Add data access to Web Forms pages. For details, see Walkthrough: Basic Data Access Using the
SqlDataSource Control in Web Pages.
 Learn about the debugger for Web pages. For details, see Walkthrough: Debugging Web Pages in
Visual Web Developer.
 Create a consistent site layout using master pages. For details, see Walkthrough: Creating and
Using ASP.NET Master Pages in Visual Web Developer.
Walkthrough: Basic HTML
Editing in Visual Studio for Web
Forms Pages
.NET Framework 4.5
Other Versions
Microsoft Visual Studio 2012 provides a rich HTML editing experience for Web Forms pages. The Visual
Studio HTML editor lets you work in WYSIWYG mode and also lets you work directly with HTML markup
for finer control. This walkthrough introduces you to the HTML editing features of Visual Studio.
Note
This topic applies to ASP.NET Web Forms pages. You can use Source view for editing pages
in ASP.NET MVC (Model View Controller)or ASP.NET Web Pages applications (.cshtml files),
but Design view is fully supported only for Web Forms pages. Web server controls are used only
in Web Forms pages.
Tasks illustrated in this walkthrough include the following:
 Creating and editing HTML in Design view.
 Creating and editing HTML in Source view.
 Using Split view.
 Using navigation tools to move quickly through your HTML tags.
Prerequisites
In order to complete this walkthrough, you need the following:
 Visual Studio or Visual Studio Express for Web installed on your computer.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 A general understanding of how to work in Visual Studio.
For an introduction to how to create Web Forms pages in Visual Studio, see Walkthrough:
Creating a Basic Web Forms Page in Visual Studio.
Creating the Web Site and Web Forms Page
If you have already created a Web Forms site in Visual Studio or Visual Studio Express for Web (for
example, by completing Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use
that web site and go to the next section. Otherwise, create a website and Web Forms page by following
these steps.
Note
This walkthrough uses a web site project. You could use a web application project instead. For
information about the difference between these web project types, see Web Application Projects
versus Web Site Projects.
To create a file system website
1. Open Visual Studio or Visual Studio Express for Web.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed, click Visual Basic or Visual C# and then select ASP.NET Empty Web Site.
For this walkthrough, you create a website that does not include prebuilt pages and other
resources.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your website.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a website project that includes a Web.config file.
6. In Solution Explorer, right-click the root of your Web site, and then click Add New Item.
7. Select Web Form, name the file Default.aspx, and then click Add.
Working in Design View
In this part of the walkthrough, you will learn how to work in Design view, which provides a WYSIWYG-
like view of the Web Forms page. You can add text by typing, as you would in a word-processing
program. You can format text directly with formatting commands or by creating in-line styles.
Design view displays your page in a way that is similar to how it will appear in a browser, with some
differences. The first difference is that in Design view, the text and elements are editable. The second
difference is that to help you edit your pages, Design view displays some elements and controls that will
not appear in the browser. Additionally, some elements, such as HTML tables, have a special Design view
rendering that adds additional space for the editor. Overall, Design view helps you visualize your page,
but it is not an exact representation of how the page will render in a browser.
To add and format static HTML in Design view
1. If you are not in Design view, click Design, which is located at the lower left of the window.
2. At the top of the page, type ASP.NET Web Page.
3. Highlight the text to select it, and then on the Formatting toolbar click Heading 1.
4. Press ENTER after ASP.NET Web Page, and then type This page is powered by ASP.NET.
5. Highlight the text, then, on the Format menu, click New Style.
The New Style dialog box appears.
6. Select the Apply new style to document selection option.
7. Select a font from the font-family drop-down list and then click Apply.
The font family is applied to the selected text.
8. Under Category, click Block, and then select (value) from the line-height drop-down list. Enter a
value for line height.
9. Select (value) from the letter-spacing dropdown list. Enter a value for letter spacing.
Click Apply to see the values applied to the selected text.
10. Click OK.
Viewing Tag Information
When you are working in Design view, you might want to see tags such as div and span that do not have
a visual rendering.
To see HTML design surface tags in Design view
 On the View menu, point to Visual Aids, and make sure that ASP.NET Non-visual Controls is
selected.
The designer displays symbols for paragraphs, line breaks, and other tags that do not render text.
The symbols are not all shown at the same time, but when you click a visual element, the
nonvisual element that precedes it is shown.
Adding Controls and Elements
In Design view, you can drag controls from the toolbox onto the page. You can add some elements, such
as HTML tables, using a dialog box. In this section, you add some controls and a table so that you have
elements to work with later in the walkthrough.
To add controls and a table
1. Put the cursor to the right of the text This page is powered by ASP.NET, and then press ENTER.
2. From the Standard group in the Toolbox, drag a TextBox control onto the page and drop it in
the space you created in the preceding step.
Note
You can also add a control by double-clicking it.
3.
4. Drag a Button control onto the page and drop it to the right of the TextBox control that you
added in the preceding step.
The TextBox and Button controls are ASP.NET web server controls, not HTML elements.
5. Put the cursor to the right of the Button control and then press ENTER.
6. On the Table menu, click Insert Table.
The Insert Table dialog box appears.
7. Click OK.
The Insert Table dialog box provides options for configuring the table that you are creating.
However, for this walkthrough, you can use a default table layout.
Creating Hyperlinks
Design view provides builders and other tools to help you create HTML elements that require property
settings.
To create a hyperlink
1. In the text This page is powered by ASP.NET, highlight ASP.NET to select it.
2. On the Format menu, click Convert to Hyperlink.
The Hyperlink dialog box appears.
3. In the URL box, type http://www.asp.net.
4. Click OK.
Setting Properties in the Properties Window
You can change the look and behavior of the elements on the page by setting values in
the Properties window.
To set properties by using the Properties window
1. Select the Button control that you added in "Adding Controls and Elements" earlier in this
walkthrough.
2. In Properties window, set Text to Click Here, and ForeColor to a different color.
3. Place the cursor in the ASP.NET hyperlink that you created in the preceding section.
Notice that in the Properties window, the hreef property for the a element is set to the URL that
you provided for the hyperlink.
Testing the Page
You can see the results of your editing by viewing the page in the browser.
To start the page in the browser externally
 Right-click the page, and then click View in Browser.
If you are prompted to save your changes, click Yes.
Visual Studio starts IIS Express, which is a local web server that you can use to test pages without
using a full IIS server.
Note
You can run pages in several ways. If you press CTRL+F5, Visual Studio performs the
start action that is configured on the property page for Start Options. The default start
option for CTRL+F5 is to run the current page; that is, the page that is currently active
in Source or Designview. You can also run pages in the debugger. For more
information, see Walkthrough: Debugging Web Pages in Visual Web Developer.
Changing the Default View
By default, Visual Studio opens new pages in Source view.
To change the default page view to Design view
1. On the Tools menu, click Options
2. Make sure that the Show all settings options is selected at the bottom of the dialog box.
3. Open the HTML Designer node and then select General. Under Start Pages in,
click Design view.
Working in Source View
Source view lets you edit the markup of the page directly. The Source view editor gives you many
features that help you as you create HTML and ASP.NET controls. You can use the toolbox in Source view
just as you do in Design view to add new elements to the page.
To add elements in Source view
1. Switch to Source view by clicking Source, which is located at the bottom of the window.
The controls that you have added are created as <asp:> elements. For example,
the Button control is the<asp:button> element. The property settings that you made are
preserved as attribute settings in the opening <asp:button> tag.
2. From the HTML group in the Toolbox (not the Standard group), drag a Table element onto the
page and place it just above the </form> tag.
The editor also helps you when you type markup manually. For example, the editor provides context-
sensitive choices that finish HTML tags and attributes as you type. The editor also provides error and
warning information on markup by underlining questionable markup with a wavy line. You can see the
error or warning information by holding the mouse over the markup text.
To edit HTML in Source view
1. Position the cursor above the closing </form> tag, and then type a left angle bracket (<).
Notice that the editor offers you a list of tags that are appropriate in the current context.
2. Enter "a" to create an anchor tag, and then press the SPACEBAR.
The editor displays a list of attributes that are appropriate for an anchor tag.
Note
The letter a (anchor element) might not appear as an option, depending on the validation
target that is set for the site or the page. However, you can still create an anchor element
by entering "a" without selecting an item in the drop-down list. Validation targets are
discussed later in this topic.
3. In the list, click href, and then type an equal sign (=) and a double quotation mark (").
The editor offers you a list of currently available pages to link to.
4. In the file list, double-click Default.aspx, press the spacebar, and then type a right angle bracket
(>) to close the tag.
The editor inserts a closing </a> tag.
5. Finish the anchor element by entering the text Home between the opening and closing tags.
The element now resembles the following example:
<a href="Default.aspx">Home</a>
6. Position the cursor just above the closing </form> tag, and then type <invalid>.
The editor underlines the tag with a wavy line, indicating that the tag is not a recognized HTML
tag.
7. Remove the tag that you created in the preceding step.
Examining HTML Formatting
An important feature of the page designer is that it preserves the HTML formatting that you apply to the
page. However, you can explicitly specify that the editor reformat the document.
To examine HTML formatting
1. Reformat the attributes for the Button control by aligning the attributes so that the declarative
syntax looks like the following:
2. <asp:Button
3. id="Button1"
4. runat="server"
5. Font-Bold="True"
6. ForeColor="Blue"
7. Text="Click Here" />
Notice that after you indent the first attribute, when you press ENTER in the tag, subsequent lines
are indented to match.
8. Switch to Design view.
9. Right-click the Button control, and then click Copy.
10. Position the cursor below the Button control, right-click, and then click Paste.
Visual Studio creates a button with the ID property set to Button2.
11. From the Standard group in the Toolbox, drag a third Button control onto the page, which
creates a button named Button3.
12. Switch to Source view.
Notice that Button2 is formatted exactly the way that you formatted Button1. On the other
hand, Button3is formatted using the default formatting for Button controls.
Note
For more information on how to customize the formatting of individual elements,
see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages.
13. Edit the document so that Button1 and Button2 are on the same line without a space between
them, as shown in the following example:
14. <asp:Button ID="Button1" runat="server" Font-Bold="True"
15. ForeColor="Blue" Text="Click Here" /><asp:Button ID="Button2"
16. runat="server" Font-Bold="True" ForeColor="Blue" Text="Click Here"/>
The elements can wrap, but the beginning of Button2 must immediately follow the end
of Button1 (the />character).
17. Switch to Design view.
Notice that Button1 and Button2 are right next to each other without a space between them.
18. Switch to Source view
19. On the Edit menu, in the Advanced submenu, click Format Document.
The document is reformatted, but Button1 and Button2 remain on the same line. If the editor
separated the buttons, it would introduce a space during rendering. Therefore, the editor does
not change the formatting that you have created.
Working in Split View
You can see both the Design view and Source view windows at the same time by using Split view.
To view a page in Split view
 Switch to Split view by clicking Split, which is located at the lower left of the window. Notice that
theSource view window occupies the upper half of the screen, and the Design view window the
lower half. Notice also that the two views are synchronized. If you double-click an item in one
view to select it, the corresponding item in the other view is highlighted.
Navigating Between Elements
As pages become larger and more complex, it is useful to be able to find tags quickly and to reduce the
clutter in the page. Visual Studio provides the following tools to help you with these tasks when you are
working in Source view:
 Document Outline, which provides a complete view of the document.
 The tag navigator, which provides information about the currently selected tag and where it is in
the page hierarchy.
To start, add more elements to the page so that you can examine the navigation features.
To add elements
1. Switch to Design view.
2. From the HTML group in the Toolbox, drag a Table control into a cell of the table that you
created in "Working in Source View," earlier in this walkthrough.
3. From the Standard group in the Toolbox, drag a Button control into the middle cell of the
nested table.
With several nested elements on the page, you can see how Document Outline provides quick
navigation to any tag in the page.
To navigate using Document Outline
1. Switch to Source view.
2. On the View menu, click Document Outline.
3. In Document Outline, click Button4.
In the editor, the <Button4> control that you added in the preceding procedure is selected.
The tag navigator provides information about the currently selected tag and where it is in the page
hierarchy.
To navigate using tag navigator
1. Position the cursor in the Button element.
Notice the tag navigator at the bottom of the window, which shows the <asp:button> tag and its
parent tags. The tag navigator includes the ID of the element, if any, so that you can identify
which element is being displayed. The tag navigator also displays the assigned cascading style
sheet, if any, that was set with the Classattribute.
2. In the tag navigator, click the <table> tag that is closest to the <asp:button#Button4> tag.
The tag navigator moves to the inner <table> element and selects it.
3. In the tag navigator, click the <td> tag to the left of the selected <table> tag.
The whole cell that contains the nested table is selected.
Note
You can click to select either the tag or its contents by using the drop-down list in the tag
navigator tag. By default, clicking a tag in the tag navigator selects the tag and its
contents.
You can also use the tag navigator to help you move or copy elements.
To move or copy elements by using the tag navigator
1. Using the tag navigator, select the <tr> tag that contains the Button4 control.
2. Press CTRL+C to copy the tag.
3. Use the tag navigator to move to the outer table.
4. In Source view, place the cursor between the <table> tag and the first <tr> tag.
5. Press CTRL+V to paste the copied row into the table.
6. Switch to Design view.
Notice that the new row has been added, including a Button control.
Formatting Text
 The Formatting toolbar applies inline styles for most settings. Bold and italic formatting is
applied by using the b and i tags. Paragraph formatting is applied a block tag, such as p (for
normal), pre (for formatted), and so on. Paragraph alignment is applied by using inline styles to
conform with XHTML 1.1 standards.
 The designer also lets you create a style block and a link to a cascading style sheet. For more
information, seeWalkthrough: Creating and Modifying a CSS File.
 By default, the editor creates markup that is compatible with the XHTML5 standard. The editor
converts all HTML tag names to lowercase, even if you type them in uppercase. The editor also
encloses attribute (property) values in double quotation marks. For more information,
see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages.
To change the default markup validation
1. In Source view, right-click the page, and then click Formatting and Validation.
2. In the Options dialog box, expand Text Editor, expand HTML, and then click Validation.
3. In the Target list, enter a validation type.
Next Steps
This walkthrough has given you an overview of the HTML capabilities of the web page editor. This
includes how to create HTML in Design view and Source view, basic formatting, and navigation. To learn
more about the editing facilities in Visual Studio, consult the following resources.
 To learn about the additional capabilities of the HTML editor, including custom formatting
options, outlining, and HTML validation, see Walkthrough: Advanced HTML Editing in Visual
Studio for Web Forms Pages.
 To learn how to work with styles in cascading style sheets, see Walkthrough: Creating and
Modifying a CSS File.
Walkthrough: Basic Data Access
Using the SqlDataSource
Control in Web Pages
Other Versions
This walkthrough shows you how to create a simple data-bound page by using controls that are specially
designed for data access.
During this walkthrough, you will learn how to do the following:
 Connect to a Microsoft SQL Server database in the Microsoft Visual Web Developer Web
development tool.
 Use drag-and-drop editing to create data-access elements that can be used in the page without
code.
 Use the SqlDataSource control to manage data access and binding.
 Display data with the GridView control.
 Configure the GridView control to allow for sorting and paging.
 Create a filtered query that displays only selected records.
A Visual Studio project with source code is available to accompany this topic: Download.
Prerequisites
In order to complete this walkthrough, you will need the following:
 Visual Studio or Visual Web Developer Express installed on your computer.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 Access to the SQL Server Northwind database. The simplest option is to use the file-based copy of
Northwind that is included in the code example download for this topic. As an alternative, you can
download and install a version of Northwind to run on an instance of SQL Server on your
computer or your local network. For information about downloading and installing the SQL Server
sample Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web
site.
Note
If you need information about how to log on to the computer running SQL Server,
contact the server administrator.
Creating the Web Site
If you have already created a Web site in Visual Studio or Visual Web Developer Express (for example, by
completingWalkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site
and go to the next section. Otherwise, create a new Web site and page by following these steps.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master
page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client
script files), and for authentication (ASP.NET membership).
Adding a GridView Control to Display Data
To display data on an ASP.NET Web page, you need the following:
 A connection to a data source (such as a database).
In the following procedure, you will create a connection to the SQL Server Northwind database.
 A data source control on the page, which executes queries and manages the results of the
queries.
 A control on the page to actually display the data.
In the following procedure, you will display data in a GridView control. The GridView control will
get its data from the SqlDataSource control.
You can add these elements to the Web site separately. However, it is easiest to start by visualizing the
data display using GridView control, and then using wizards to create the connection and data source
control. The following procedure explains how to create all three of the elements that you must have to
display data on the page.
To add and configure a GridView control for displaying data
1. In Visual Web Developer, switch to Design view.
2. From the Data folder in the Toolbox, drag a GridView control onto the Default.aspx page.
3. If the GridView Tasks shortcut menu does not appear, right-click the GridView control, and then
click Show Smart Tag.
4. On the GridView Tasks menu, in the Choose Data Source list, click <New data source>.
The Data Source Configuration dialog box appears.
5. Click Database.
This specifies that you want to obtain data from a database that supports SQL statements. This
includes SQL Server and other OLE-DB–compatible databases.
In the Specify an ID for the data source box, a default data source control name appears
(SqlDataSource1). You can leave this name.
6. Click OK.
The Configure Data Source wizard appears, displaying a page on which you can choose a
connection.
7. Click New Connection.
8. In the Choose Data Source dialog box, under Data source, click Microsoft SQL Server, and then
clickContinue.
The Add Connection dialog box appears.
9. In the Server name box, enter the name of the SQL Server that you want to use.
10. For the logon credentials, select the option that is appropriate for accessing the SQL Server
database (integrated security or specific ID and password) and if it is required, enter a user name
and password.
11. Click Select or enter a database name, and then enter Northwind.
12. Click Test connection, and when you are sure that it works, click OK.
The Configure Data Source - <DataSourceName> wizard appears and the connection
information is filled in.
13. Click Next.
The wizard appears, displaying a page on which you can choose to store the connection string in
the configuration file. Storing the connection string in the configuration file has two advantages:
o It is more secure than storing the connection string in the page.
o You can reuse the same connection string in multiple pages.
14. Make sure that the Yes, save this connection as check box is selected, and then click Next. (You
can leave the default connection string name of NorthwindConnectionString.)
The wizard appears, displaying a page on which you can specify the data that you want to fetch
from the database.
15. Under Specify columns from a table or view, in the Name list, click Customers.
16. Under Columns, select the CustomerID, CompanyName, and City check boxes.
The wizard appears, displaying the SQL statement that you are creating in a box at the bottom of
the page.
Note
The wizard lets you specify selection criteria (a WHERE clause) and other SQL query
options. For this part of the walkthrough, you will create a simple statement without
selection or sort options.
17. Click Next.
18. Click Test Query to make sure that you are fetching the data you want.
19. Click Finish.
The wizard closes and you are returned to the page. Running the wizard has accomplished two
tasks:
o The wizard created and configured a SqlDataSource control (named SqlDataSource1),
which incorporates the connection and query information that you specified.
o The wizard bound the GridView control to the SqlDataSource. Therefore,
the GridView control will display data that is returned by the SqlDataSource control.
If you view the properties for the SqlDataSource control, you can see that the wizard has created
values for theConnectionString and SelectQuery properties.
Note
You can easily change the look of the GridView control. In Designview, right-click
the GridView control, and then click Show Smart Tag. On the GridView Tasks menu,
click Auto Format, and then apply a scheme.
Testing the Page
You can now run the page.
To test the page
1. Press CTRL+F5 to run the page.
The page appears in the browser. The GridView control displays all data rows from the Customers
table.
2. Close the browser.
Adding Sorting and Paging
You can add sorting and paging to the GridView control without writing any code.
To add sorting and paging
1. In Design view, right-click the GridView control, and then click Show Smart Tag.
2. On the GridView Tasks shortcut menu, select the Enable Sorting check box.
The column headings in the GridView control change to links.
3. On the GridView Tasks menu, select the Enable Paging check box.
A footer is added to the GridView control with page number links.
4. Optionally, use Properties to change the value of the PageSize property from 10 to a smaller
page size.
5. Press CTRL+F5 to run the page.
You will be able to click a column heading to sort by the contents of that column. If there are
more records in the data source than the page size of the GridView control, you will be able to
use the page navigation links at the bottom of the GridView control to move between pages.
6. Close the browser.
Adding Filtering
Frequently you want to display only selected data in the page. In this part of the walkthrough, you will
modify the query for the SqlDataSource control so that users can select customer records for a particular
city.
First, you will use a TextBox control to create a text box in which users can type the name of a city. Then,
you will change the query to include a parameterized filter (WHERE clause). As part of that process, you
will create a parameter element for the SqlDataSource control. The parameter element establishes how
the SqlDataSource control will get the value for its parameterized query—namely, from the text box.
When you are finished with this part of the walkthrough, the page might look similar to the following
in Design view.
To add the text box for specifying a city
1. From the Standard group in the Toolbox, drag a TextBox control and a Button control onto the
page.
The Button control is used only to post the page to the server. You will not need to write any
code for it.
2. In Properties, for the TextBox control, set ID to textCity.
3. If you want, type City or similar text before the text box to act as a caption.
4. In Properties for the Button control, set Text to Submit.
You can now modify the query to include a filter.
To modify the query with a parameterized filter
1. Right-click the SqlDataSource control, and then click Show Smart Tag.
2. On the SqlDataSource Tasks menu, click Configure Data Source.
The Configure Data Source - <Datasourcename> wizard appears.
3. Click Next.
The wizard displays the SQL command that is currently configured for the SqlDataSource control.
4. Click WHERE.
The Add WHERE Clause page appears.
5. In the Column list, click City.
6. In the Operator list, click =.
7. In the Source list, click Control.
8. Under Parameter properties, in the Control ID list, click textCity.
The previous five steps specify that the query will get the search value for City from
the TextBox control that you added in the preceding procedure.
9. Click Add.
The WHERE clause that you have created appears in a box at the bottom of the page.
10. Click OK to close the Add WHERE Clause page.
11. In the Configure Data Source - <DataSourceName> wizard, click Next.
12. On the Test Query page, click Test Query.
The wizard appears, displaying the Parameter Values Editor page, which prompts you for a value
to use in the WHERE clause.
13. In the Value box, type London, and then click OK.
The customer records for London appear.
14. Click Finish to close the wizard.
You can now test filtering.
To test filtering
1. Press CTRL+F5 to run the page.
2. In the text box, type London, and then click Submit.
A list of customers from the city of London appears in the GridView control.
3. Try other cities, such as Buenos Aires and Berlin.
Walkthrough: Creating
Master/Detail Web Pages in
Visual Studio
Other Versions
Many Web pages display data in more than one way, often displaying data from related tables. This
walkthrough shows you various ways to work with data in multiple controls and from multiple tables,
including those that have a master/detail relationship. Tasks illustrated in this walkthrough include:
 Populating a drop-down list with database data.
 Creating filters — SQL statements with a WHERE clause (parameterized queries).
 Displaying filtered data based on the user's selection in a drop-down list.
 Displaying details about a selected record using the DetailsView control.
 Selecting a record in one page and displaying a related record in a second page.
Prerequisites
In order to complete this walkthrough, you will need:
 Visual Studio or Visual Web Developer.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 Access to the SQL Server Northwind database. For information about downloading and installing
the SQL Server sample Northwind database, see Installing Sample Databases on the Microsoft
SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server,
contact the server administrator.
 Microsoft Data Access Components (MDAC) version 2.7 or later.
If you are using Microsoft Windows XP or Windows Server 2003 or a later version of Windows,
you already have MDAC 2.7. However, if you are using Microsoft Windows 2000, you might to
need to upgrade the MDAC already installed on your computer. For more information, see the
article " Microsoft Data Access Components (MDAC) Installation" in the MSDN Library.
Creating the Web Site
If you have already created a Web site project (for example, by following the steps in Walkthrough:
Creating a Basic Web Forms Page in Visual Studio or Walkthrough: Basic Data Access Using the
SqlDataSource Control in Web Pages), you can use that Web site and skip to the next section,
"Connecting to SQL Server." Otherwise, create a new Web site and page by following these steps.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Studio or Visual Web Developer.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master
page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client
script files), and for authentication (ASP.NET membership).
Connecting to SQL Server
To work with data, you need to establish a connection to a database. In this walkthrough, you will create a
connection independently of working with Web pages or controls.
To create a connection to SQL Server
1. Press CTRL+ALT+S to display the Database Explorer. In Database Explorer, right-click Data
Connectionsand choose Add Connection.
The Change Data Source dialog box is displayed.
2. In the Change Data Source dialog box, select Microsoft SQL Server. and click OK.
3. In the Add Connection dialog box, do the following:
o Enter or select the name of your SQL Server computer. For a server on your computer,
enter (local).
o Select Use SQL Server Authentication.
o Enter a user name and password.
o Select Save my password.
o Select Northwind as the database.
4. Click Test Connection, and when you are sure that it works, click OK.
The connection is added to Server Explorer.
Using a Drop-Down List as the Master
In this part of the walkthrough, you will add a drop-down list to a page and populate it with a list of
categories from the Northwind table. When users select a category, the page will display the products for
that category.
To create and populate a drop-down list
1. Switch to or open the Default.aspx page. If you are working with a Web site you had already
created, add or open a page that you can work with in this walkthrough.
2. Switch to Design view.
3. Type Select Products By Category in the page and format the text as a heading using the Block
Formatdrop-down list above the Toolbox.
4. From the Standard group in the Toolbox, drag a DropDownList control onto the page.
5. In the DropDownList Tasks, select the Enable AutoPostBack check box.
This configures the control so that it causes the page to post back to the server whenever a
selection is made from the list, rather than waiting until the user clicks a button.
6. In the DropDownList Tasks, select Choose Data Source.
The Choose Data Source wizard starts.
7. In the Select a data source list, click <New Data Source>.
The Data Source Configuration Wizard dialog box is displayed.
8. Select Database.
This specifies that you want to get data from a database that supports SQL statements. (This
includes SQL Server and other OLE-DB-compatible databases.)
In the Specify an ID for the data source box, a default data source control name is displayed
(SqlDataSource1). You can leave this name.
9. Click OK.
The wizard displays the Configure Data Source - SqlDataSource1 page in which you can select
a data connection.
10. From the drop-down list, select the Northwind connection you created earlier in the
walkthrough.
11. Click Next.
The wizard displays a page in which you can choose to store the connection string in the
configuration file.
12. Be sure the Yes, save this connection as check box is selected, and then click Next. (You can
leave the default connection string name.)
The wizard displays a page in which you can specify what data you want to retrieve from the
database.
13. From the Name list under Table or View Options, select Categories.
14. In the Columns box, select CategoryID and CategoryName.
15. Click Next.
16. Click Test Query to be sure that you are getting the data you want.
17. Click Finish.
The Data Source Configuration Wizard is displayed, with the name of the data source control
you have configured displayed.
18. From the Select a data field to display in the DropDownList list, select CategoryName.
Note
If no items appear in the list, click the Refresh Schema link.
19. This specifies that the value of the CategoryName field will be displayed as the text of the item in
the drop-down list.
20. From the Select a data field for the value of the DropDownList list, select CategoryID.
This specifies that when an item is selected, the CategoryID field will be returned as the value of
the item.
21. Click OK.
Before proceeding, test the drop-down list.
To test the drop-down list
1. Press CTRL+F5 to run the page.
2. When the page is displayed, examine the drop-down list.
3. Select a category to be sure that the list performs a postback.
You can now display products for the category selected in the drop-down list.
Using a Grid to Display Detail Information
You can now extend the page to include a grid. When users make a selection from the categories drop-
down list, the grid will display the products for that category.
To use a grid to display detail information
1. Switch to or open the Default.aspx page (or the page you have been working with), and switch to
Design view.
2. From the Data group of the Toolbox, drag a GridView control onto the page.
3. From the GridView Tasks menu, select <New Data Source> from the Choose Data Source list.
The Data Source Configuration Wizard opens.
4. Select Database.
In the Specify an ID for the data source box, a default data source control name is displayed
(SqlDataSource2). You can leave this name.
5. Click OK.
The wizard displays a page where you can select a connection.
6. From the connections drop-down list, select the connection you created and stored earlier in the
walkthrough (NorthwindConnectionString).
7. Click Next.
The wizard displays the Configure Data Source - SqlDataSource2 page in which you can create
a SQL statement.
8. From the Name list, select Products.
9. In the Columns box, select ProductID, ProductName, and CategoryID.
10. Click WHERE.
The Add WHERE Clause dialog box is displayed.
11. From the Column list, select CategoryID.
12. From the Operator list, select =.
13. From the Source list, select Control.
14. Under Parameter Properties, in the Control ID list, select DropDownList1.
The last two steps specify that the query will get the search value for the category ID from
the DropDownListcontrol you added earlier.
15. Click Add.
16. Click OK to close the Add WHERE Clause dialog box.
17. Click Next.
18. In the Preview page, click Test Query.
The wizard displays a dialog box that prompts you for a value to use in the WHERE clause.
19. Type 4 in the box and click OK.
The products records for category 4 are displayed.
20. Click Finish to close the wizard.
You can now test the master/detail display.
To test the page
1. Press CTRL+F5 to run the page.
When the page appears, products from the first item in the drop-down list are displayed.
2. Select a category from the list and confirm that the corresponding products appear in the grid.
Displaying Master/Detail Data on the Same Page
In this part of the walkthrough, you will display data from related tables in one page. The master table
data is displayed in a grid where users can select individual rows. When they do, one or more detail
records are displayed in a scrollable control elsewhere on the page. For illustration purposes, you will use
the Northwind Categories table as the master table and the Products table as the details table.
To display the master records
1. Add a new page to the Web site and name it MasterDetails2.aspx.
2. Switch to Design view.
3. Type Master/Detail Page in the page and format the text as a heading.
4. From the Data group of the Toolbox, drag a GridView control onto the page.
5. In the GridView Tasks menu, in the Choose Data Source list, click <New Data Source> and
then use these steps to configure a data source for the GridView control:
a. Select Database.
b. Click OK.
c. From the connection drop-down list, select the connection you created and stored earlier
in the walkthrough (NorthwindConnectionString).
d. Click Next.
e. From the Name list, select Categories.
f. In the Columns box, select CategoryID and CategoryName.
g. Click Next and then click Finish.
6. Select the GridView control, and in the GridView Tasks menu, choose Edit Columns.
The Fields dialog box is displayed.
7. Under Available Fields, open the Command Field node, choose Select, and then click Add to
add it to theSelected Fields list.
8. In the Selected Fields list, choose Select, and then in the CommandField property grid, set
its SelectTextproperty to Details.
9. Click OK to close the Fields dialog box.
A new column with a Details hyperlink is added to the grid.
10. Select the GridView control and in the Properties window, be sure its DataKeyNames property is
set toCategoryID.
This specifies that when you select a row in the grid, ASP.NET can find the key of the currently
displayed Categories record in a known location.
The grid allows you to select an individual category. The next step is to add the DetailsView control that
will display the detail records — the products associated with the selected category.
The DetailsView control will use a different SQL query to get its data, so it requires a second data source
control.
To configure a query to display related records
1. Press ENTER to make space underneath the SqlDataSource1 control on the MasterDetails2.aspx
page in Details view.
2. From the Data group of the Toolbox, drag a DetailsView control onto the page.
3. Configure it to use a second data source control using the following steps:
a. From the Choose Data Source list, select <New Data Source>.
b. Select Database.
c. Click OK.
d. In the connection drop-down list, click the connection you created and stored earlier in
the walkthrough.
e. Click Next.
f. From the Name list under Table or View Options, select Products.
g. In the Columns box, select ProductID, ProductName, and CategoryID.
h. Click WHERE.
The Add WHERE Clause dialog box is displayed.
i. From the Column list, select CategoryID.
j. From the Operator list, select =.
k. From the Source list, select Control.
l. Under Parameter Properties, in the Control ID list, select GridView1. The query for the
second grid will get its parameter value from the selection in the first grid.
m. Click Add and then click OK to close the Add WHERE Clause dialog box.
n. Click Next.
o. In the Preview page, click Test Query.
The wizard displays a dialog box that prompts you for a value to use in the WHERE clause.
p. Type 4 in the box and click OK.
The products records for category 4 are displayed.
q. Click Finish.
4. In the DetailsView Tasks menu, check Enable Paging.
This will allow you to scroll through individual product records.
5. Optionally, in the Properties window, open the PagerSettings node and select a
different Mode value.
By default, you page through records by clicking a page number, but you can select options to
use next and previous links.
You can now test the combination of the master grid and the details view.
To test the page
1. Press CTRL+F5 to run the page.
2. In the grid, select a category.
The DetailsView control displays a product associated with that category.
3. Use the pager links in the DetailsView control to navigate to other products for the same
category.
4. In the grid, select a different category.
5. Review the products for that category in the DetailsView control.
Displaying Master/Detail Data on Separate Pages
For the final part of the walkthrough, you will create another variation — displaying master and detail
records on separate pages. The master records are again displayed in a grid that contains a hyperlink for
each record. When users click the hyperlink, they navigate to a second page where they can view detail
records in a DetailsView control that displays the complete Products record.
To display the master records
1. Add a new page to the Web site and name it MasterCustomers.aspx.
2. Switch to Design view.
3. Type Customers in the page and format the text as a heading.
4. From the Data folder of the Toolbox, drag a GridView control onto the page.
5. From the GridView Tasks menu on the control, choose <New Data Source> from the Choose
Data Sourcelist and then use the wizard to do the following:
o Click Database.
o Connect to the Northwind database (connection NorthwindConnectionString).
o Retrieve the CustomerID, CompanyName, and City columns from the Customers table.
6. Optionally, on the GridView Tasks menu, select the Enable paging check box.
7. In the GridView Tasks menu, choose Edit Columns.
The Fields dialog box is displayed.
8. Clear the Auto-Generate Fields check box.
9. Under Available Fields, choose HyperLink Field, click Add, and then set the following
properties:
Property Value
Text Details
DataNavigateUrlFields CustomerID
This indicates that the hyperlink should get its value
from theCustomerID column
DataNavigateUrlFormatString DetailsOrders.aspx?custid={0}
This creates a link that is hard-coded to navigate to
the DetailsOrders.aspx page. The link also passes a
query string variable named custid whose value will
be filled using the column referenced in
the DataNavigateUrlFields property.
10. Click OK to close the Fields dialog box.
You can now create the details page that accepts a value from the master page.
To create the details page
1. Add a new page to the Web site and name it DetailsOrders.aspx.
2. Switch to Design view.
3. Type Orders in the page and format the text as a heading.
4. From the Data folder of the Toolbox, drag a GridView control onto the page.
5. In the GridView Tasks menu on the control, select <New Data Source> from the Choose Data
Source list
6. In the Select a data source type list, click Database and then click OK.
7. From the connection list, select the connection you created and stored earlier in the walkthrough
(NorthwindConnectionString).
8. Click Next.
The wizard displays a page where you can create a SQL statement.
9. From the Name list, select Orders.
10. In the Columns box, select OrderID, CustomerID, and OrderDate.
11. Click WHERE.
12. From the Columns list, select CustomerID.
13. From the Operators list, select =.
14. From the Source list, select QueryString.
This specifies that the query will select records based on the value passed into the page with the
query string.
15. Under Parameter Properties, in the QueryString field box, type custid.
The query will get the customer ID value from the query string, which is created when you click
a Details link in the MasterCustomers.aspx page.
16. Click Add.
17. Click OK to close the Add WHERE Clause dialog box.
18. Click Next, and then click Finish to close the wizard.
19. From the Standard node of the Toolbox, drag a Hyperlink control onto the page. Set
its Text property toReturn to Customers and its NavigateUrl property
to MasterCustomers.aspx.
You can now test the related master-detail pages.
To test the pages
1. Switch to the MasterCustomers.aspx page.
2. Press CTRL+F5 to run the page.
3. Click the Details link for a customer.
The browser displays the DetailsOrders.aspx page with the order for the selected customer. Note
that the URL in the browser's Address box is:
DetailsOrder.aspx?custid=x
where x is the ID of the customer you selected.
4. Click the Return to Customers link, select a different customer, and click the Details link again to
test that you can view orders for any customer.
Walkthrough: Editing and
Inserting Data in Web Pages
with the DetailsView Web
Server Control
Other Versions
Microsoft Visual Web Developer allows you to create data entry forms for updating records and inserting
new ones into a database with only a few lines of code. By using a combination of a data source control
that encapsulates data access and DetailsView and GridView controls that display records in an editable
format, you can create a data entry page that allows users to edit existing records or insert new ones, all
without any code.
A Visual Studio project with source code is available to accompany this topic: Download.
During this walkthrough, you will learn how to:
 Create a data entry page.
 Configure a data source control with information required to make database updates and inserts.
 Use the DetailsView control to view individual records, change them, and insert new ones.
 Use a GridView control to enable database modification from the data entry page.
Prerequisites
In order to complete this walkthrough, you will need:
 Visual Studio or Visual Web Developer Express.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 Microsoft Data Access Components (MDAC) version 2.7 or later.
If you are using the Microsoft Windows XP or Windows Server 2003 operating systems or later,
you already have MDAC 2.7. However, if you are using the Microsoft Windows 2000 Server
operating system, you might need to upgrade the MDAC already installed on your computer. To
download the current MDAC version, see the Data Developer Center on the MSDN Web site.
 Access to the SQL Server Northwind database. For information about downloading and installing
the SQL Server sample Northwind database, see Installing Sample Databases on the Microsoft
SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server,
contact the server administrator.
 Permission to modify data in the sample Northwind database.
Creating the Web Site and Page
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a new file system Web site
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master
page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client
script files), and for authentication (ASP.NET membership).
Connecting to SQL Server
The next step is to establish a connection to the SQL Server database.
To create a connection to a SQL Server database
1. In Server Explorer, right-click Data Connections, and then click Add Connection. If you are using
Visual Web Developer Express, use Database Explorer.
The Add Connection dialog box appears.
o If the Data source list does not display Microsoft SQL Server (SqlClient), click Change,
and in theChange Data Source dialog box, select Microsoft SQL Server.
o If the Choose Data Source page appears, in the Data source list, select the type of data
source you will use. For this walkthrough, the data source type is Microsoft SQL Server.
In the Data provider list, click.NET Framework Data Provider for SQL Server, and the
click Continue.
Note
If the Server Explorer tab is not visible in Visual Web Developer, in the View menu,
click Server Explorer. If the Database Explorer tab is not visible in the Express
edition, in the View menu, click Database Explorer.
2. In the Add Connection box, enter your server name in the Server Name box.
3. For the Log on to the server section, select the option that is appropriate to access the running
the SQL Server database (integrated security or specific ID and password) and, if required, enter a
user name and password. Select the Save my Password check box if you entered a password.
4. Under Select or enter a database name, enter Northwind.
5. Click Test Connection, and when you are sure that it works, click OK.
Your new connection has been created under Data Connections in Server Explorer.
Creating the Data Entry Page
In this section, you will create a data entry page and configure a DetailsView control so that you can view
employee data that is stored in the Employees table of the Northwind database. To handle the data
access for the page, you will configure a SQL data source control.
To create a data entry page and configure a DetailsView control
1. On the Website menu, click Add New Item.
The Add New Item dialog box appears.
2. Under Installed Templates, click Visual C# or Visual Basic, and then select Web Form.
3. In the Name box, type EditEmployees.aspx.
4. Click Add.
The EditEmployees.aspx page opens in Source view.
5. Switch to Design view.
6. Type Edit Employees, select the text, and then format the text as a heading.
7. In the Toolbox, from the Datagroup, drag a DetailsView control onto the page.
8. Right-click the DetailsView control, click Properties, and then set AllowPaging to true.
This will allow you to page through individual employee entries when they are displayed.
The next step is to create and configure a data source control that can be used to query the database.
There are a number of ways to create a data source control, including dragging data elements from Server
Explorer or Database Explorer onto the page. In this walkthrough, you will start with
the DetailsView control and configure the data source control from there.
To configure a data source control
1. Right-click the DetailsView control and click Show Smart Tag.
2. On the DetailsView Tasks menu, in the Choose Data Source box, click <New data source>.
The Data Source Configuration Wizard dialog box appears.
3. Under Select a data source type, click Database.
4. Leave the default name of SqlDataSource1, and then click OK.
The Configure Data Source wizard displays the Choose a connection page.
5. In the Which data connection should your application use to connect to the database? box,
enter the connection that you created in "To create a connection to SQL Server," and then
click Next.
The wizard displays a page where you can choose to store the connection string in a
configuration file. Storing the connection string in the configuration file has two advantages:
o It is more secure than storing it in the page.
o You can use the same connection string in multiple pages.
6. Select the Yes, save this connection as check box, and then click Next.
The wizard displays a page where you can specify what data you want to retrieve from the
database.
7. On the Configure the Select Statement page, select Specify columns from a table or view,
and then in theName box, click Employees.
8. Under Columns, select the EmployeeID, LastName, FirstName, and HireDate check boxes, and
then clickNext.
9. Click Test Query to preview the data, and then click Finish.
You can now test the employee records display page.
To test displaying the employee records
1. Press CTRL+F5 to run the page.
The first employee record is displayed in the DetailsView control.
2. Click the page number links to see additional employee records.
3. Close the browser.
Allowing Editing in a GridView Control
At this point, you can view employee records, but you cannot edit them. In this section, you will add
a GridViewcontrol and configure it so that you can edit individual records.
Note
The GridView control presents a list of records and allows you to edit them. However, it does
not allow you to insert them. Later in this walkthrough, you will use the DetailsView control,
which allows you to add new records.
To support editing, you must configure the data source control you created earlier (SqlDataSource1) with
SQL statements that perform updates.
To add a GridView control to allow editing
1. In the Toolbox, from the Data group, drag a GridView control onto the page.
2. Right-click the GridView control, click Show Smart Tag, and then on the GridView Tasks menu,
in theChoose Data Source box, click SqlDataSource1.
3. On the GridView Tasks menu, click Configure Data Source.
4. Click Next to advance to the Configure the Select Statement page of the wizard.
5. On the Configure the Select Statement page, click Advanced, select the Generate INSERT,
UPDATE, and DELETE statements check box, and then click OK.
This generates Insert, Update, and Delete statements for the SqlDataSource1 control based on the
Select statement that you configured earlier.
Note
Alternatively, you could manually create the statements by selecting Specify a custom
SQL statement or stored procedure and entering SQL queries.
6. Click Next, and then click Finish.
The SqlDataSource control is now configured with additional SQL statements.
Note
You can examine the statements generated by the wizard by selecting
the SqlDataSource control and viewing the DeleteQuery, InsertQuery,
and UpdateQuery properties. You can also view the updated control properties by
switching to Source view and examining the markup of the control.
7. On the GridView Tasks menu, select the Enable Paging and Enable Editing check boxes.
Security Note
User input in an ASP.NET Web page can include potentially malicious client script. By
default, ASP.NET Web pages validate user input to make sure input does not include
script or HTML elements. As long as this validation is enabled, you do not need to
explicitly check for script or HTML elements in user input. For more information,
see Script Exploits Overview.
You can now test the editing of employee records.
To test the editing in the GridView control
1. Press CTRL+F5 to run the page.
The GridView control is displayed with the data in text boxes.
2. Choose a row in the GridView control and click Edit.
3. Make a change to the record, and then click Update.
The updated data now appears in both the GridView control and the DetailsView control.
4. Close the browser.
Allowing Editing, Deleting, and Inserting Using a
DetailsView Control
The GridView control allows you to edit records, but it does not allow you to insert data. In this section,
you will modify the DetailsView control so that you can see records individually, as well as delete, insert,
and update records.
To use a DetailsView control to allow deleting, inserting, and updating
1. Right-click the DetailsView control and then click Show Smart Tag.
2. On the DetailsView Tasks menu, select the Enable Inserting, Enable Editing, and Enable
Deleting check boxes.
When you used the DetailsView control earlier in the walkthrough, the options for enabling
editing, inserting, and deleting were not available. The reason is that the SqlDataSource1 control
that the DetailsView control is bound to did not have the necessary SQL statements. Now that
you have configured the data source control to include update statements, the update options
are available on the DetailsView control.
You can now test deleting, inserting, and updating in the DetailsView control.
To test the updating, inserting, and deleting in the DetailsView control
1. Press CTRL+F5 to run the page.
The DetailsView control displays an employee record.
2. In the DetailsView control, click Edit.
The DetailsView control now displays the data in text boxes.
3. Make a change to the record, and then click Update.
The updated record is displayed in the control.
4. In the DetailsView control, click New.
The control now displays blank text boxes for each column.
5. Enter values for each column.
The Employees table has an auto-increment key column, so the value for EmployeeID is assigned
automatically when you save the record.
6. When you are finished, click Insert.
The new record is added as the last record.
Note
Inserting a new record in the Employees table in this walkthrough will not generate any
errors. However, when you work with production data, the tables might have constraints
(such as a foreign key constraint) that you must be aware of when configuring
the DetailsView control.
7. Use paging in the DetailsView control to navigate to the last record, and then click Delete.
The new record is removed.
Note
As with inserting data, you must always be aware of any constraints that apply to the data
row when configuring a DetailsView control to allow deletion.
Walkthrough: Using the
ObjectDataSource with an XML
File
Other Versions
Many Web applications are built by using multiple tiers, with one or more components in the middle tier
to provide data access. Creating a custom middle tier business object allows you to implement your own
business logic. This walkthrough illustrates how to create a basic business object that you can use as a
data source for ASP.NET Web Forms pages.
During this walkthrough, you will learn how to:
 Create a component that can return data to a Web page. The component uses an XML file for its
data.
 Reference the business object as a data source on a Web page.
 Bind a control to the data returned by the business object.
 Read and write data by using the business object.
Prerequisites
In order to complete this walkthrough, you will need:
 Visual Web Developer (Visual Studio).
 The .NET Framework.
This walkthrough assumes that you have a general understanding of how to use Visual Web Developer.
Creating the Web Site
If you have already created a Web site in Visual Web Developer (for example, by following the steps
in Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and go to
the next section, "Creating an XML File for Business Data." Otherwise, create a new Web site and page.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click NewWeb Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web
site.
For example, type the folder name C:WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating an XML File for Business Data
In the following procedure, you will create a simple XML file for the business component data.
To create the XML file
1. In Solution Explorer, right-click App_Data, and then click AddNew Item.
Note
Be sure you create the XML file in the App_Data folder. The App_Data folder has
permissions set on it that will allow the Web page to read and write data to the XML file.
2. Under Visual Studio installed templates, click XML file.
3. In the Name box, type Authors.xml.
4. Click Add.
A new XML file is created that contains only the XML directive.
5. Copy the following XML data, and then paste it into the file, overwriting what is already in the file.
The XML file includes schema information that identifies the database structure of the data,
including a primary-key constraint for the key.
Note
Business components can work with data in any way that is suitable for your application.
This walkthrough uses an XML file.
<?xml version="1.0" standalone="yes"?>
<dsPubs xmlns="http://www.tempuri.org/dsPubs.xsd">
<xs:schema id="dsPubs"
targetNamespace="http://www.tempuri.org/dsPubs.xsd"
xmlns:mstns="http://www.tempuri.org/dsPubs.xsd"
xmlns="http://www.tempuri.org/dsPubs.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-
microsoft-com:xml-msdata" attributeFormDefault="qualified"
elementFormDefault="qualified">
<xs:element name="dsPubs" msdata:IsDataSet="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="authors">
<xs:complexType>
<xs:sequence>
<xs:element name="au_id" type="xs:string" />
<xs:element name="au_lname" type="xs:string" />
<xs:element name="au_fname" type="xs:string" />
<xs:element name="au_phone" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
<xs:unique name="Constraint1" msdata:PrimaryKey="true">
<xs:selector xpath=".//mstns:authors" />
<xs:field xpath="mstns:au_id" />
</xs:unique>
</xs:element>
</xs:schema>
<authors>
<au_id>172-32-1176</au_id>
<au_lname>West</au_lname>
<au_fname>Paul</au_fname>
<au_phone>408 555-0123</au_phone>
</authors>
<authors>
<au_id>213-46-8915</au_id>
<au_lname>Gray</au_lname>
<au_fname>Chris</au_fname>
<au_phone>415 555-0120</au_phone>
</authors>
</dsPubs>
6. Save the Authors.xml file, and then close it.
Creating a Component
The next step is to create a class to act as your business component. You will keep the component in
the App_Codefolder of your Web site. In a real application, you can keep the component in any
convenient store, including the global assembly cache. If your Web site does not already have a directory
named App_Code, you must create one.
To create an App_Code folder
 In Solution Explorer, right-click the name of your Web site, click Add ASP.NET Folder, and then
clickApp_Code.
Note
The folder must be named App_Code.
You can now add the component to your site.
To create the business component
1. In Solution Explorer, right-click the App_Code folder, and then click Add New Item.
Note
Be sure to create the new item in the App_Code folder.
2. The Add New Item dialog box appears.
3. Under Visual Studio installed templates, click Class.
4. In the Language box, click the programming language you prefer.
5. In the Name box, type BusinessObject.
6. Click Add.
Visual Web Developer creates the new class file and opens the code editor.
7. Copy the following code, and then paste it into the file, overwriting what is already in the file.
C#
VB
using System;
using System.Web;
using System.Data;
namespace PubsClasses
{
public class AuthorClass
{
private DataSet dsAuthors = new DataSet("ds1");
private String filePath =
HttpContext.Current.Server.MapPath
("~/App_Data/Authors.xml");
public AuthorClass()
{
dsAuthors.ReadXml (filePath, XmlReadMode.ReadSchema);
}
public DataSet GetAuthors ()
{
return dsAuthors;
}
}
}
Note
Make sure the value of the filePath variable references the name of the XML file that
you created previously.
When an instance of the class is created, it reads the XML file and translates it into a dataset. The
class'sGetAuthors method returns the dataset.
8. Save the file. You must save the file for the next section to work properly.
Displaying Data by Using the Business Component
You can now invoke the business component in a Web page and display its data. To reference the
component, you use an ObjectDataSource control, which is specifically designed to work with objects.
To create an ObjectDataSource control that references the component
1. Switch to or open the Default.aspx page.
Note
If you do not have a Default.aspx page, you can use another page. Alternatively, you can
add a new page to the Web site. In Solution Explorer, right-click the name of your Web
site, click Add New Item, and then add a Web Form.
2. Switch to Design view.
3. In the Toolbox, from the Data folder, drag an ObjectDataSource control onto the page.
4. In the Properties window, set ID to AuthorsObjectDataSource.
5. Right-click the ObjectDataSource control, and then click the smart tag to display
the ObjectDataSource Tasks menu.
6. On the ObjectDataSource Tasks menu, click Configure Data Source.
The Configure Data Source wizard appears.
7. In the Choose your business object list, click PubsClasses.AuthorClass.
8. Click Next.
9. In the Select tab, in the Choose a method list, click GetAuthors(), returns Dataset.
The GetAuthors method is defined in the business class you created previously. It returns a
dataset containing the data from the Authors.xml file.
10. Click Finish.
The configuration information you have entered specifies that to get data from the component,
the component's GetAuthors method should be called.
Note
The name of the method you specify for the SelectMethod property is case-sensitive,
even if you are programming in Visual Basic .NET.
You can now get data from the component by using the ObjectDataSource control. You will display the
data in aGridView control on the page.
To display data from the component
1. In the Toolbox, from the Data folder, drag a GridView control onto the page.
2. Right-click the GridView control, and then click the smart tag if the Common GridView
Tasks menu is not showing.
3. On the Common GridView Tasks menu, in the Choose Data Source box,
click AuthorsObjectDataSource.
4. Press CTRL+F5 to run the page.
The GridView control with the XML data in it is displayed.
Inserting Data by Using the Business Component
As with other data source controls, such as the SqlDataSource control, the ObjectDataSource control
supports updating (inserting, updating, and deleting). In this section, you will modify the business
component with a method that inserts an author record. Then you will change the page so that users can
type new author information and modify the ObjectDataSource control to perform the insertion.
Note
During this part of the walkthrough, the Authors.xml file you created previously will be updated.
It is important that the application have permission to write to the file at run time or the Web
page will display an error when you try to update the file. If you created the Authors.xml file in
the App_Data folder, permissions are set automatically.
To modify the business component to allow inserts
1. Switch to the BusinessObject file.
2. Add the following method as the final member of AuthorClass.
C#
VB
public void InsertAuthor (String au_id, String au_lname,
String au_fname, String au_phone)
{
DataRow workRow = dsAuthors.Tables[0].NewRow ();
workRow.BeginEdit ();
workRow[0] = au_id;
workRow[1] = au_lname;
workRow[2] = au_fname;
workRow[3] = au_phone;
workRow.EndEdit ();
dsAuthors.Tables[0].Rows.Add (workRow);
dsAuthors.WriteXml (filePath, XmlWriteMode.WriteSchema);
}
Note
Pay close attention to the names of the variables used to pass author information into the
method (au_id,au_lname, au_fname, and au_phone). They must match the column
names defined in the schema of the XML file you created previously.
The new method takes four values to insert, which you will provide in the page as parameters. The
method creates a new row in the dataset, and then writes the updated dataset out as an XML file.
3. Save the file.
The next step is to change the page so that users can enter new author information. For the following
procedure, you will use the DetailsView control.
To add a control for inserting data
1. Switch to or open the Default.aspx page.
2. Switch to Design view.
3. In the Toolbox, from the Data folder, drag a DetailsView control onto the page.
Note
The exact layout of the page is not important.
4. On the DetailsView Tasks menu, in the Choose Data Source box,
click AuthorsObjectDataSource.
Note
If the DetailsView Tasks menu is not visible, click the smart tag.
5. In the Properties window, set AutoGenerateInsertButton to true.
This causes the DetailsView control to render a New button that users can click to put the
control into data-entry mode.
Finally, you must configure the ObjectDataSource control to specify what action the control should take to
insert data.
To configure the data source control for inserting data
 Right-click AuthorsObjectDataSource, click Properties, and then
set InsertMethod to InsertAuthor.
This is the name of the method that you added to the business component.
You can now insert new authors into the XML file.
To test insertion
1. Press CTRL+F5 to run the Default.aspx page.
2. In the DetailsView control, click the New button.
The control is redisplayed with text boxes.
3. Enter new author information, and then click Insert.
The new author information is added to the XML file. The GridView control immediately reflects
the new record.
Walkthrough: Debugging Web
Pages in Visual Web Developer
Other Versions
Visual Studio provides you with tools to help track down errors in your ASP.NET Web pages. In this
walkthrough, you will work with the debugger, which allows you to step through the page's code line by
line and examine the values of variables.
In the walkthrough, you will create a Web page that contains a simple calculator that squares a number.
After creating the page (which will include a deliberate error), you will use the debugger to examine the
page as it is running.
Tasks illustrated in this walkthrough include:
 Setting breakpoints.
 Invoking debugger from a Web Forms page in a file system Web site.
Prerequisites
In order to complete this walkthrough, you will need:
 Microsoft Visual Studio or Microsoft Visual Web Developer Express and the .NET Framework.
You should also have a general understanding of working in Visual Studio. For an introduction to Visual
Studio, seeWalkthrough: Creating a Basic Web Forms Page in Visual Studio.
Creating the Web Site and Page
In the first part of the walkthrough, you will create a page that you can debug.
If you have already created a Web site in Visual Studio (for example, by working with the
topic Walkthrough: Creating a Basic Web Forms Page in Visual Studio ), you can use that Web site and
skip to "Adding Controls to Debug" later in this walkthrough. Otherwise, create a new Web site and page.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Studio.
2. On the File menu, click NewWeb Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, click File System and then type the name of the folder where you want to
keep the pages of your Web site.
For example, type the folder name C:WebSites.
5. In the Language list, click the programming language that you prefer to work in.
The programming language you choose will be the default for your Web site. However, you can
use multiple languages in the same Web application by creating pages and components in
different programming languages. For information on creating components using different
languages, see Shared Code Folders in ASP.NET Web Site Projects.
6. Click OK.
Visual Studio creates the folder and a new page named Default.aspx.
Creating a Page to Debug
You will begin by creating a new page. For this walkthrough, it is important that you create a new page as
specified in the following procedure.
To add a page to the Web site
1. Close the Default.aspx page.
2. In Solution Explorer, right-click the name of your Web site (for example, C:WebSite) and
choose Add New Item.
3. Under Visual Studio installed templates, choose Web Form.
4. In the Name box, type DebugPage.aspx.
5. From the Language list, choose the programming language you prefer to use.
6. Be sure that the Place code in separate file check box is cleared.
In this walkthrough, you are creating a single-file page with the code and HTML in the same page.
The code for ASP.NET pages can be located either in the page or in a separate class file. To learn
more about keeping the code in a separate file, see Walkthrough: Creating a Basic Web Forms
Page with Code Separation in Visual Studio .
7. Click Add.
Visual Studio creates the new page and opens it in Source view.
You can now add some controls to the page and then add code. The code will be simple, but enough to
allow you to add breakpoints later.
To add controls and code for debugging
1. Switch to Design view, and then from the Standard folder of the Toolbox, drag the following
controls onto the page and set their properties as indicated:
Control Properties
Label ID: CaptionLabel
Text: (empty)
TextBox ID: NumberTextBox
Text: (empty)
Button ID: SquareButton
Text: Square
Label ID: ResultLabel
Text: (empty)
Note
For this walkthrough, the layout of the page is not
important.
2. Double-click the Button control to create a Click handler for it.
3. Add logic to the Click handler to call a function called Square to square the number entered by
the user. The handler might look like the following example.
Note
The code example deliberately does not include error checking.
4. C#
5. VB
6. protected void SquareButton_Click(object sender, System.EventArgs e)
7. {
8. int number, result;
9. number = System.Convert.ToInt32(NumberTextBox.Text);
10. result = Square(number);
11. ResultLabel.Text = NumberTextBox.Text +
12. " squared is " + result.ToString();
13. }
14. Create the function that squares the number. Include a bug in the code to add the number to
itself instead of multiplying it. The code might look like the following example.
C#
VB
int Square(int number )
{
int Square;
Square = number + number;
return Square;
}
You can also add code to the page that will change the text of the label depending on whether this is the
first time the page is running.
To change the caption Label control
1. In Design view, double-click the design surface (not a control) to create a Page_Load event
handler.
2. Set the text of the Caption Label control to Enter a number: if this is the first time the page is
running, orEnter another number: otherwise. The handler will look like the following code
example.
C#
VB
if(Page.IsPostBack == false)
{
CaptionLabel.Text = "Enter a number: ";
}
else {
CaptionLabel.Text = "Enter another number: " ;
}
Testing the Page
To make sure the page is working, run it in its current state.
To run the page
1. Save the page.
2. Press CTRL+F5 to run the page.
3. Enter the number 3 and press the Square button.
Note that the result is incorrect, because there is a bug in the program. The correct result is 9.
4. Close the browser.
Debugging the Page
In this part of the walkthrough, you will use the debugger to examine the page code line by line as it is
running, add breakpoints to the code, and then run the page in Debug mode.
You will start by setting breakpoints in your code. A breakpoint is a line in your code where execution
stops and the debugger is invoked.
To set breakpoints
1. Switch to Source view.
2. Right-click the following line, choose Breakpoint, and then choose Insert Breakpoint.
Note
You can toggle breakpoints by pressing F9.
3. C#
4. VB
5. if(Page.IsPostBack == false)
6. Set another breakpoint on the following line of the SquareButton_Click handler:
C#
VB
result = Square(number);
Note
You cannot set a breakpoint on a statement that declares a variable.
With at least one breakpoint set, you are ready to run the debugger.
To run the debugger
1. From the Debug menu, choose Start Debugging (or press F5) to run the page in debug mode.
If you have never run the debugger before, your application probably is not configured to
support debugging. By default, debugging is turned off in applications both for performance
(pages run more slowly in the debugger) and for security reasons. Visual Studio displays a
message telling you what it must do to enabled debugging.
The switch to enable debugging is stored as a setting in the Web.config file, which maintains
various site-specific configuration options. If the Web.config file does not exist, Visual Studio will
both create the file and make the appropriate debugger setting.
If the Web.config file already exists but debugging is not enabled, you will see a slightly different
message telling you that Visual Studio will modify the Web.config file.
2. If you see the message telling you that debugging has not been enabled, click OK to enable
debugging.
In Visual Studio, the designer changes to debug mode displaying the code for your page and
some debugger windows.
The debugger runs your page line by line. When the debugger gets to the line with the
breakpoint, it stops and highlights the line.
Because the breakpoint is in the Page_Load handler, the page has not finished processing yet.
The browser is open, but the page is not yet displayed.
3. In the Debug menu, click Windows, click Watch, and then click Watch 1.
Note
If you are using Visual Web Developer Express, the debugger offers only a
single Watch window.
4. This opens a Watch window, where you can specify the values you want to track.
5. In the editor, right-click the IsPostBack portion of the Page.IsPostBack expression, and then
clickAdd Watch.
This adds the expression to the Watch window and displays the current value of the property
(false) is displayed in the Value column. If you prefer, you can type the name of a variable or
property in the Namecolumn of the Watch window.
6. From the Debug menu, choose Continue to continue execution, or press F5.
The Continue command tells the debugger to proceed until it gets to the next breakpoint.
The Page_Loadevent handler finishes processing and the page is displayed in the browser.
7. Enter the value 2 into the text box and click the Square button.
The debugger is displayed again, with the breakpoint on the line in the Page_Load handler. This
time, theWatch window shows you that the value of Page.IsPostBack is true.
8. Press F5 again to continue.
The debugger processes the Page_Load handler and enters the SquareButton_Click handler,
where it stops on the second breakpoint you set.
9. In the Debug menu, click Windows and then click Locals.
This opens the Locals window, which displays the values of all variables and objects that are in
scope at the current line being executed. The Locals window provides an alternative way for you
to view these values, with the advantage that you do not have to explicitly set a watch on the
elements, but with the disadvantage that the window might contain more information than you
want to see at once.
In the Locals window, you see that the value of number is 2 and the value of result is 0.
Note
You can also see the value of any variable in the program by holding the mouse pointer
over it.
10. In the Value column of the Locals window, right-click the line for the number variable and
select Edit value. Edit the value of the number variable and change it to 5.
The value 2 for the variable number is not a good test of the program, because adding and
squaring 2 both result in 4. Therefore, while the program is running, you can change the value of
this variable.
11. From the Debug menu, choose Step Into to step into the Square function, or press F11.
The Step Into command causes the debugger to execute a line and then stop again.
12. Continue stepping by pressing F11 until you reach the following line of code.
C#
VB
ResultLabel.Text = NumberTextBox.Text +
" squared is " + result.ToString();
The debugger walks through your code line by line. When the debugger executes
the Square function, you can use the Locals window to check the data passed to the function
(number) and the return value of the function (Square).
13. In the Debug menu, click Windows and then Immediate.
The Immediate window allows you to execute commands. You can use the window to evaluate
expressions (for example, to get the value of a property).
14. In the Immediate window, type the following expression and press Enter.
15. ? NumberTextBox.Text
The question mark (?) is an operator in the Immediate window that evaluates the expression
following it. In this example, you are evaluating the Text property of the NumberTextBox control
on the page. You can evaluate any variable, object property, or expression that combine these,
using the same syntax that you would use in code.
16. In the Immediate window, type the following and press Enter:
17. NumberTextBox.Text = "5"
In addition to evaluating expressions, the Immediate window allows you to change variables or
properties
18. Press F5 to continue running the program.
When the page appears, it displays the result of passing 5 to the Square function. In addition, the
text in the text box has been changed to 5.
The result you see — 10 — is not correct, since 10 is not the square of 5. You can now fix the bug.
To fix the bug and test again
1. Switch from the browser to Visual Studio.
Note
Do not close the browser window.
2. In the Square function, change the "+" operator to the "*" operator.
Because the code is not currently running (the page has finished processing), you are in edit
mode and can make permanent changes.
3. Press CTRL+S to save the page.
4. From the Debug menu, choose Delete All Breakpoints so that the page will not stop each time
you run it.
Note
You can also clear breakpoints by pressing CTRL+SHIFT+F9.
5. Switch to the browser window.
6. Enter 5 in the text box and click the button.
This time, when you run the page and enter a value, it is squared correctly. The temporary
changes you made earlier, such as changing the Text property of the NumberTextBox control,
have not been persisted, because they applied only when the page was running the last time.
7. Close the browser to stop the debugger.
Walkthrough: Creating and
Using ASP.NET Master Pages in
Visual Web Developer
Other Versions
This walkthrough illustrates how to create a master page and several content pages. Master pages allow
you to create a page layout — a template page — and then create separate pages containing content
that is merged with the master page at run time. For more information about master pages, see ASP.NET
Master Pages.
A Visual Studio project with source code is available to accompany this topic: Download.
Note
By default, the ASP.NET Web Site project template includes prebuilt functionality, which
includes a master page. However, this walkthrough uses the ASP.NET empty Web site project
template to show you how to manually add a master page to a Web site.
Tasks illustrated in this walkthrough include:
 Creating a master page.
 Creating an ASP.NET page that contains content that you want to display in the master page.
 Selecting a master page at run time.
Prerequisites
In order to complete this walkthrough, you will need:
 Visual Studio or Microsoft Visual Web Developer Express.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 Optionally, a .jpg, .gif, or other graphics file that you can use as a logo on your master page. It is
recommended that the logo be no more than 48 pixels wide. However, displaying a logo is
optional and the graphic's exact size is not critical to the walkthrough.
Creating a Web Site
If you have already created a Web site in Visual Web Developer (for example, by following the steps
in Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and skip to
the next section, Creating the Master Page. Otherwise, create a new Web site and page.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or VisualC# and then select ASP.NET Empty Web
Site.
4. In the Weblocation box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates an Web site project that includes a Web.config file.
Creating the Master Page
The master page is the template for how your pages will look. In this section, you will first create a master
page. You will then use a table to lay out the master page with a menu, a logo, and a footer that will
appear on each page of your site. You will also work with a content placeholder, which is a region in the
master page that can be replaced with information in a content page.
To create the master page
1. In Solution Explorer, right-click the name of your Web site, and then click AddNew Item.
2. Under Visual Studio installed templates, click Master Page.
3. In the Name box, type Master1.
4. Select the Place code in separate file check box.
Note
This walkthrough assumes you are using code-behind files for all pages. If you are using
a single-file ASP.NET page, the code illustrated in this walkthrough will work, but will
appear in Source view, not in a separate code file.
5. In the Language list, click the programming language you prefer and then click Add.
The new master page opens in Source view.
At the top of the page is an @ Master declaration instead of the @ Page declaration normally
found at the top of ASP.NET pages. The body of the page contains a ContentPlaceHolder control,
which is the area of the master page where replaceable content will be merged from content
pages at run time. You will work more with the content placeholder later in this walkthrough.
Laying Out the Master Page
The master page defines how the pages in your site look. It can contain any combination of static text and
controls. A master page also contains one or more content placeholders that designate where dynamic
content will appear when pages are displayed.
In this walkthrough, you will use a table to help you position elements on the page. You will start by
creating a layout table to hold the master page elements. Later in this section you will position the
content placeholder control that is already on the page.
To create a layout table for the master page
1. With the Master1.master file selected in Source view, use the Target Schema for
Validation drop-down list on the toolbar to set the target schema to Microsoft Internet
Explorer 6.0.
2. Switch to Design view.
3. Click on the center of the page to select the page. From the Properties window,
set BgColor property to a distinctive color, such as blue.
The color you select is not important. Later in this walkthrough you will create a second master
page without a color to contrast with what you have selected here.
4. Click the page where you want to place the layout table.
Note
Do not put the layout table inside the ContentPlaceHolder control.
5. On the Table menu, click Insert Table.
6. In the Insert Table dialog box, create a table with three rows and one column, and then click OK.
7. Place the cursor inside the second row of the table.
8. On the Table menu, in the Modify submenu, click Split Cells.
9. In the Split Cells dialog box, select Split into columns, and then click OK.
10. Make the following settings:
o In the middle row, click the leftmost column, and then set its Width to 48 in
the Properties window.
o Click the top row, and then set its Height to 48 in the Properties window.
o Click the bottom row, and then set its Height to 48 in the Properties window.
Note
You can set the width and height by dragging the table cell borders or by selecting
the cell and setting values in the Properties window.
11. Select all cells in the table and set BgColor to a different color than the background color.
After laying out the table, you can add content to the master page that will appear on all pages. You will
add a copyright message as a footer, and then add a menu. If you have a logo graphic available, you can
add that as well.
To add static content to the master page
1. Click the bottom cell, and then type footer text such as Copyright 2007 Contoso Inc.
2. In the Toolbox, from the Navigation control group, drag a Menu control into the top cell.
3. Create a menu by following these steps:
a. Set the Menu control's Orientation property to Horizontal.
b. Click the smart tag on the Menu control, and click Edit Menu Items in the Menu
Tasks dialog box. TheEdit Menu Items dialog box appears.
4. In the Edit Menu Items dialog box, in the Items section, click the Add a root node icon twice to
add two menu items:
a. Click the first node, and then set Text to Home and NavigateUrl to Default.aspx.
b. Click the second node, and then set Text to About and NavigateUrl to About.aspx.
c. Click OK to close the Menu Item Editor dialog box.
5. If you have a graphics file available to use as a logo, follow these steps to place it on the master
page:
a. In Solution Explorer, right-click the name of your Web site, and then click Add Existing
Item.
b. Navigate to your graphics file, select the graphic file, and then click Add.
c. In the Toolbox, from the Standard group, drag an Image control to the middle left
column of the table.
d. Set the Image control's ImageUrl property to the name of the graphics file.
You can now position the content placeholder to specify where the master page can display content at
run time.
To move the content placeholder
1. Drag the ContentPlaceHolder control into the middle right cell. You can move the control by
clicking inside the control and then dragging it by its tag.
The control's ID property is ContentPlaceholder1. You can leave this name or change it. If you
change the name, make a note of the name because you will need to know the name later.
2. Save the page.
Creating Content for the Master Page
The master page provides the template for your content. You define content for the master page by
creating an ASP.NET page that is associated with the master page. The content page is a specialized form
of an ASP.NET page that contains only the content to be merged with the master page. In the content
page, you add the text and controls that you want to display when users request that page.
In this walkthrough, you will add two pages with content for the master page. The first is a default (home)
page and the second is an about page.
To create the Default page
1. In Solution Explorer, right-click the name of your Web site, and click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, keep the file name that Visual Studio inserts: Default.
4. In the Language list, click the programming language you prefer.
5. Select the Select master page check box, and then click Add.
The Select a Master Page dialog box appears.
6. Click Master1.master, and then click OK.
A new .aspx file is created. The page contains an @ Page directive that attaches the current page
to the selected master page with the MasterPageFile attribute, as shown in the following code
example.
C#
VB
<%@ Page Language="C#" MasterPageFile="~/Master1.master" ... %>
The page also contains an Content control element that you will work with next.
A content page does not have the usual elements that make up an ASP.NET page, such as html, body,
or formelements. Instead, you add only the content that you want to display on the master page by
replacing the placeholder regions you created in the master page.
To add content to the Default page
1. In Source view, type Contoso Home Page in the Title element of the @ Page directive at the top
of the page.
You can set the title of each content page independently, so that the correct title is displayed in
the browser when the content is merged with the master page. The title information is stored in
the content page's@ Page directive.
2. Switch to Design view.
The ContentPlaceHolder controls in the master page are displayed as Content controls in the new
content page. The rest of the master page content is displayed so that you can see the layout.
However, it appears dimmed because you cannot change it while you are editing a content page,
and the cursor becomes the I-bar only where you can add content.
3. In the Content control that matches ContentPlaceHolder1 on the master page, type Welcome
to the Contoso Web Site.
4. Select the text then format it as a heading by selecting Heading 1 from the Block Format drop-
down list above the Toolbox.
5. Press ENTER to create a new blank line in the Content control, and then type Thank you for
visiting our site.
The text you add here is not important; you can type any text that will help you recognize this
page as the Default (home) page.
6. Save the page.
You can create the About page the same way you created the Default page.
To create the About page
1. Use the same steps that you used for the Default page to add a new content page named
About.aspx.
Be sure to attach the new page to the Master1.master page as you did with the Default page.
2. Change the page's title to Contoso About Page.
3. In the content region, type About Contoso, and then format the text as a Heading 2 by selecting
the text and selecting Heading 2 from the Block Format drop-down list above the Toolbox.
4. Press ENTER to create a new line, and then type Since 1982, Contoso has provided high-quality
software services.
5. Save the page.
Testing the Pages
You can test the pages by running them as you would any ASP.NET page.
To test the pages
1. Switch to the Default.aspx page, and then press CTRL+F5.
ASP.NET merges the content in the Default.aspx page with the layout in the Master1.master page
into a single page and displays the resulting page in the browser.
2. Click the About link.
The About.aspx page is displayed. It is also merged with Master1.master page.
Referencing Master Page Members
Code in the content pages can reference members on the master page, including any public properties or
methods and any controls on the master page. In this part of the walkthrough, you will create a property
on the master page, and then use the value of the property in the content pages. The premise is that the
company name for the Web site is stored as a property in the master page, and any reference to the
company name in the content pages is based on the master page property.
The first step is to add a property to the master page.
To add a property to the master page
1. Switch to or open the Master1.master page.
2. In Solution Explorer, right-click Master1.master, and then click View Code to open the code
editor.
Note
By default, Visual Web Developer creates pages that use the code-behind model.
3. Inside the class definition, type the following code.
C#
VB
public String CompanyName
{
get { return (String) ViewState["companyName"]; }
set { ViewState["companyName"] = value; }
}
The code creates a property named CompanyName for the master page. The value is stored in view
state so that it is persisted between postbacks.
4. Inside the class definition (but not inside the property code), add the following code.
C#
VB
void Page_Init(Object sender, EventArgs e)
{
this.CompanyName = "Contoso";
}
For this example, you will hard-code the value of the CompanyName property into the page.
You can now modify the content page to use the master page's CompanyName property.
To reference the CompanyName property in the content page
1. Switch to or open the Default.aspx page.
2. Switch to Source view.
3. At the top of the page, underneath the @ Page directive, add the
following @ MasterType directive:
4. <%@ MasterType virtualpath="~/Master1.master" %>
The directive binds the content page's Master property, which you will use shortly, to the
Master1.master page.
5. Switch to Design view.
6. In the Content control, change the text to Welcome to the Web site of .
7. In the Toolbox, from the Standard group, drag a Label control onto the Content control, and
place it after the static text so that the text reads:
Welcome to the Web site of [Label]
8. Set the Label control's ID property to CompanyName.
9. In Solution Explorer, right-click Default.aspx, and then click View Code to open the code editor.
10. Inside the class definition, add the following code.
C#
VB
void Page_Load(Object sender, EventArgs e)
{
CompanyName.Text = Master.CompanyName;
}
The content page's Master property returns a reference to the master page as defined in
the @ MasterTypedirective you added in step 3.
You can now test the content page to be sure it is referencing the master page's CompanyName property
correctly.
To test the reference to the master page property
1. Switch to or open the Default.aspx page, and then press CTRL+F5 to run the page.
The page is displayed in the browser, with the text Welcome to the Web site of Contoso
2. Close the browser.
3. Switch to or open the Master1.master code-behind page.
4. Change the Page_Init handler to assign a different company name to the property, as in the
following code example.
C#
VB
void Page_Init(Object sender, EventArgs e)
{
this.CompanyName = "New Company Name";
}
5. Switch to the Default.aspx page, and then press CTRL+F5 to run it again.
This time, the updated company name appears in the page.
Changing Master Pages Dynamically
Under some circumstances, you might want to be able to change master pages dynamically; that is, to use
code to set the master page for a content page. For example, you might want to let users select from
several layouts and set the master page according to their preferences.
In this part of the walkthrough, you will add a second master page to the Web site, and then create
buttons that allow the user to switch between one master page and another. Because the two master
pages will be very similar, you will make a copy of the first master page and modify it to act as the second
master page.
To make a copy of the master page
1. In Solution Explorer, right-click Master1.master, and then click Copy.
2. Right-click the name of the Web site, and then click Paste.
A master page is added to the Web site with the name Copy of master1.master.
3. Right-click Copy of master1.master, click Rename, and then name the new master
page Master2.master.
4. Open Master2.master and, in the @ Master directive, change Master1 to Master2.
The completed page directive will look like the following code example:
C#
VB
<%@ Master Language="C#" CodeFile="Master2.master.cs"
Inherits="Master2" %>
5. Switch to Design view.
6. In the Properties window, in the drop-down list at the top, click DOCUMENT.
7. Change the BgColor property to a color visibly different than the color you chose for Master1.
The new master page will look and function like Master1.master, but will have a different
background color.
8. Open the code file for Master2.master and change the class name in the master page's code-
behind file fromMaster1 to Master2 to match the value of the Inherits attribute in the
page's @ Master directive.
The code will look like the following example:
C#
VB
public partial class Master2 : System.Web.UI.MasterPage
The next step is to add a button to each master page that allows the user to select the alternate master
page.
To add buttons for selecting an alternate master page
1. Switch to or open the Master2.master page.
2. In the Toolbox, from the Standard node, drag a LinkButton control onto the page and place it
below the menu in the top table cell.
3. Set the button's Text property to First Color.
4. Double-click the button to create a handler for its Click event, and then add the following
highlighted code.
C#
VB
protected void LinkButton1_Click(Object sender, EventArgs e)
{
Session["masterpage"] =
"Master1.master";Response.Redirect(Request.Url.ToString());
}
The code loads the file name of the alternate master page into a persistent session variable, and
then reloads the current page. (The Url property returns a Uri object that references the current
page.) Shortly, you will create code in the content page that will use the name of the master page.
5. Switch to or open the Master1.master page in Design view.
6. Add a LinkButton control as you did in steps 1 and 2, and set its Text property to Second Color.
7. Double-click the Plain button to create a handler for its Click event, and then add the following
highlighted code.
C#
VB
protected void LinkButton1_Click(Object sender, EventArgs e)
{
Session["masterpage"] =
"Master2.master";Response.Redirect(Request.Url.ToString());
}
This code is the same as that for the button in the Master2.master page, except that it loads an
alternate master page.
You can now write code in the content page that will dynamically load the master page that the user has
selected.
To write code to dynamically select the master page
1. Switch to or open the About.aspx page.
Note
The Default page you have already created contains an @ MasterType directive that
effectively binds it to a single master page (Master1.master). Therefore, you will not be
able to assign master pages dynamically to the Default page and will instead work with
other pages you have created.
2. In Solution Explorer, right-click About.aspx, and then click View Code to open the code editor.
3. Inside the class definition, add the following code.
C#
VB
void Page_PreInit(Object sender, EventArgs e)
{
if(Session["masterpage"] != null)
{
this.MasterPageFile = (String) Session["masterpage"];
}
}
The code sets the value of the current page's MasterPageFile property to the value in the session
variable, if any. This code must run in the Page_PreInit handler; it cannot run in a handler that
occurs any later than thePage_PreInit handler (for example, in the Page_Init handler), because
the master page must be established so that the page can create an instance of it before any
further initialization can occur.
You can now test the dynamic master pages.
To test the dynamic master pages
1. In the About.aspx page, press CTRL+F5 to run the page.
The page is displayed in the browser merged with its default master page, Master1.master.
2. Click the Second Color link.
The page is redisplayed, this time merged with Master2.master, which has no background color.
3. Click the First Color link.
The page is displayed using Master1.master again.
Notes on Using Master Pages
There are several other issues you should be aware of when working with a master page:
 In a real-world application, you would probably store information such as the company name in
the configuration file and read it directly in the content pages. However, the scenario outlined
here provides a simple illustration of how to reference master page members in content pages.
 You can access members on the master page even without including an @ MasterType directive.
However, to do so, you must cast the Page.Master property to the appropriate master page type
(the Master property is null if a page has no master page). For more information, see Working
with ASP.NET Master Pages Programmatically.
You can reference controls on the master page by using the Master.FindControls method. For more
information, see Working with ASP.NET Master Pages Programmatically.
There are several other issues you should be aware of when working with dynamic master pages:
 The scenario in this section for changing master pages is simplified to keep the walkthrough
focused on master pages. In a real application, you would most likely display a choice of layouts,
and then store the user's preference by using profiles. For details, see ASP.NET Profile Properties
Overview.
 You can configure your Web site so that all pages use the same master page. You might have a
few pages that should use an alternate master page, which you can configure in code in a manner
similar to that shown in this section of the walkthrough. For details, see "Scoping Master Pages"
in ASP.NET Master Pages.
 You need to add the code from the Default.aspx page to every page where you want to override
the default master page.
Walkthrough: Adding Site
Navigation to a Web Site
Other Versions
In any site that has more than just several pages, it can be difficult to construct a navigation system that
lets users move freely between pages, especially as you change the site. ASP.NET site navigation lets you
create a centralized site map of the pages.
This walkthrough shows you how to configure a site map and how to use controls that rely on the site
map to add navigation to pages in the Web site.
During this walkthrough, you will learn how to do the following:
 Create a Web site that has example pages and a site-map file that describes the layout of the
pages.
 Use the TreeView control as a navigation menu that lets users jump to any page in your site.
 Use the SiteMapPath control to add a navigation path, also known as a breadcrumb, that enables
a user to view and move back up the site hierarchy from the current page.
 Use the Menu control to add a navigation menu that lets users view one level of nodes at a time.
Pausing the mouse pointer over a node that has child nodes generates a submenu of the child
nodes.
 Use site navigation and controls on a master page so that you have to define the site navigation
only once.
A Visual Studio Web site project with source code is available to accompany this topic: Download.
Prerequisites
In order to complete this walkthrough, you will need the following:
 Microsoft Visual Web Developer Web development tool.
 The .NET Framework.
This walkthrough assumes that you know how to use Visual Web Developer.
Creating a Web Site That Has Example Pages and a Site
Map
If you have already created a Web project in Visual Web Developer by completing Walkthrough: Creating
a Basic Web Forms Page in Visual Studio, you can use that project and go to the next section. Otherwise,
create a new Web site project and page by following these steps.
Note
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects
versus Web Site Projects in Visual Studio.
Creating a File System Web Site
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site (or on the File menu, click New, and then click Web Site).
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the left-most Location box, click File System, and then in the right-most Location box, enter
the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:WebSitesSiteNavigation.
5. In the Language box, click the programming language that you prefer to work in.
The programming language that you choose will be the default for the Web site, but you can set
the programming language for each page individually.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating a Site Map
To use site navigation, you need a way to describe how the pages in your site are laid out. The default
method is to create an .xml file that contains the site hierarchy, including the page titles and URLs.
The structure of the .xml file reflects the structure of your site. Each page is represented as
a siteMapNodeelement in the site map. The top-most node represents the home page, and child nodes
represent pages that are deeper in the site.
To create a site map
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. In the Add New Item <Path> dialog box:
a. Under Visual Studio installed templates, click Site Map.
b. In the Name box, Make sure that the name is Web.sitemap.
Note
The file must be named Web.sitemap and must appear in the root of the Web site.
c. Click Add.
3. Copy the following XML content into the Web.sitemap file, overwriting the default contents.
4. <siteMap>
5. <siteMapNode title="Home" description="Home" url="~/home.aspx" >
6. <siteMapNode title="Products" description="Our products"
7. url="~/Products.aspx">
8. <siteMapNode title="Hardware"
9. description="Hardware we offer"
10. url="~/Hardware.aspx" />
11. <siteMapNode title="Software"
12. description="Software for sale"
13. url="~/Software.aspx" />
14. </siteMapNode>
15. <siteMapNode title="Services" description="Services we offer"
16. url="~/Services.aspx">
17. <siteMapNode title="Training" description="Training"
18. url="~/Training.aspx" />
19. <siteMapNode title="Consulting" description="Consulting"
20. url="~/Consulting.aspx" />
21. <siteMapNode title="Support" description="Support"
22. url="~/Support.aspx" />
23. </siteMapNode>
24. </siteMapNode>
25. </siteMap>
The Web.sitemap file contains a set of siteMapNode elements that are nested to three levels. The
structure of each element is the same. The only difference among them is the location within the
XML hierarchy.
The URL of the pages that are defined in the sample .xml file is unqualified. This means that all
pages are treated as having URLs that are relative to the application root. However, you can
specify any URL for a specific page — the logical structure that you define in the site map does
not have to correspond to the physical layout of the pages in folders.
26. Save the file, and then close it.
Creating Pages to Navigate
In this section, you will create only a few of the pages that are described in the site map that you defined
in the preceding section. (The site map is more complete so that you will be able to view a full hierarchy
when testing the pages in this walkthrough.)
To create pages to navigate
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. In the Add New Item <Path> dialog box:
a. Under Visual Studio installed templates, click Web Form.
b. In the Name box, type Home.aspx, and then click Add.
3. Switch to Design view.
4. On the Home.aspx page, type Home, and then format it as a Heading 1.
Repeat this procedure and create four additional pages named Products.aspx, Hardware.aspx,
Software.aspx, and Training.aspx. Use the name of the page (for example, Products) as the
heading so that you will be able to recognize each page when the page is displayed in the
browser.
It is not important which pages you specifically create. The pages that are listed in this procedure
are suggestions that will let you see the site hierarchy nested to three levels.
Creating a Navigation Menu Using the TreeView Control
Now that you have a site map and some pages, you can add navigation to your site. You will use
the TreeViewcontrol to act as a collapsible navigation menu.
To add a tree-style navigation menu
1. Open the Home.aspx page.
2. From the Data group in the Toolbox, drag a SiteMapDataSource control onto the page.
In its default configuration, the SiteMapDataSource control retrieves its information from the
Web.sitemap file that you created in "Creating a Site Map," earlier in this walkthrough, so that you
do not have to specify any additional information for the control.
3. From the Navigation group in the Toolbox, drag a TreeView control onto the page.
4. On the TreeView Tasks menu, in the Choose Data Source box, click SiteMapDataSource1.
5. Save the page.
Testing the Tree Style Navigation Menu
You can now perform an interim test of your navigation system.
To test the navigation menu
1. Press CTRL+F5 to run the Home.aspx page.
The tree shows two levels of nodes.
2. Click Products to view the Products page.
o If you did not create a Products.aspx page, click the link for a page that you did create.
In the current state of the Web site, the navigation menu appears only on the Home page. You could add
the sameSiteMapDataSource and TreeView controls to each page in the application to display a
navigation menu on each page. However, later in this walkthrough, you will see how to place the
navigation menu on a master page so that the navigation menu automatically appears with every page.
Displaying Navigation History Using the SiteMapPath
Control
Besides creating a navigation menu by using the TreeView control, you can add navigation on each page
that displays where the page is in the current hierarchy. This kind of navigation control is also known as a
breadcrumb. ASP.NET provides the SiteMapPath control that can automatically implement page
navigation.
To display navigation history
1. Open the Products.aspx page and switch to Design view.
2. From the Navigation group in the Toolbox, drag a SiteMapPath control onto the page, place the
cursor in front of the SiteMapPath control, and then press ENTER to create a new line.
The SiteMapPath control displays the position of the current page in the page hierarchy. By
default, theSiteMapPath control represents the hierarchy that is created in the Web.sitemap file.
For example, when you display the Products.aspx page, the SiteMapPath control displays the
following path:
Home > Products
3. Repeat this procedure for the other pages that you have created in this walkthrough, except the
Home page.
Even if you do not put a SiteMapPath control on each page, for testing purposes you need a
control on a page at each level of the site hierarchy (for example, on the Products.aspx and
Hardware.aspx pages).
Testing Navigation History
You can test page navigation by viewing pages that are at the second and third levels of the hierarchy.
To test page navigation
1. Open the Home.aspx page, and then press CTRL+F5 to run the page.
2. Use the TreeView control to move to the Products page.
At the location in the page where you put the SiteMapPath control, you see a path that is similar
to the following:
Home > Products
3. Click Home to return to the Home page.
4. Use the TreeView control to move to the Hardware page.
This time you see a path that is similar to the following:
Home > Products > Hardware
All page names that are displayed by the SiteMapPath control are links, except the last one, which
represents the current page. You can make the current node into a link by setting
the RenderCurrentNodeAsLink property of theSiteMapPath control to true.
The SiteMapPath control lets users move back up the site hierarchy, but it does not allow for them to
jump to a page that is not in the current hierarchy path.
Creating a Navigation Menu Using the Menu Control
Besides creating a navigation menu by using the TreeView control, you can use the Menu control to
display an expandable navigation menu that lets users view one level of nodes at a time. Pausing the
mouse pointer over a node that has child nodes generates a submenu of the child nodes.
To add a menu-style navigation menu
1. Open the Products.aspx page and switch to Design view.
2. From the Navigation group in the Toolbox, drag a Menu control onto the page.
3. On the Menu Tasks menu, in the Choose Data Source box, click NewDataSource.
4. In the Configure Data Source — <Datasourcename> wizard, click Site Map, and then click OK.
5. Save the page.
Testing the Menu Style Navigation Menu
You can now perform an interim test of your navigation system.
To test the navigation menu
1. Close Menu Tasks.
2. Open the Home.aspx.
3. Press CTRL+F5 to run the Home.aspx page.
The tree shows two levels of nodes.
4. Click Products to view the Products page.
o If you did not create a Products.aspx page, click the link for a page that you did create.
5. On the navigation menu, rest the mouse pointer on the Home link to expand the menu.
In the current state of the Web site, the navigation menu appears only on the Home page. You could add
the sameSiteMapDataSource and Menu controls to each page in the application to display a navigation
menu on each page. However, in the next section of this walkthrough, you will see how to put the
navigation menu on a master page so that it automatically appears with each page.
Combining Site Navigation with Master Pages
In the pages that you have created up to this point in this walkthrough, you have added site navigation
controls individually to each page. Doing this is not especially complex, because you do not have to
configure the controls differently for each page. However, it can add to the maintenance costs for your
site. For example, to change the location of the SiteMapPath control for pages in your site, you would
have to change each page individually.
By using site navigation controls in combination with master pages, you can create a layout that contains
the navigation controls in one location. You can then display pages as content within the master page.
To create the master page for navigation
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. In the Add New Item <Path> dialog box:
a. Under Visual Studio installed templates, click Master Page.
b. In the Name box, type Navigation.master, and then click Add.
3. Switch to Design view.
The master page appears with a default ContentPlaceHolder control.
In the following procedure, you will create a master page with a simple layout for navigation controls. In a
real application, you would likely use more sophisticated formatting, but the techniques for using
navigation controls on a master page will be similar.
To add navigation controls to the master page
1. Select the ContentPlaceHolder control, press LEFT ARROW, and then press ENTER.
This inserts a blank line in front of the ContentPlaceHolder control.
2. From the Data group in the Toolbox, drag a SiteMapDataSource control onto the master page
and position it above the ContentPlaceHolder control.
Note
Do not position the SiteMapDataSource control on the ContentPlaceHolder control.
3. By default, the SiteMapDataSource control will use the Web.sitemap file that you created in
"Creating a Site Map," earlier in this walkthrough.
4. Click the SiteMapDataSource control, press RIGHT ARROW, and then press ENTER.
This inserts a blank line under the SiteMapDataSource control.
5. On the Table menu, click Insert Table, and then insert a table that has one row, two columns,
and a width of 100 percent.
6. From the Navigation group in the Toolbox, drag a TreeView control onto the left cell of the
table.
7. On the TreeView Tasks menu, in the Choose Data Source box, click SiteMapDataSource1.
8. From the Navigation group in the Toolbox, drag a SiteMapPath control onto the right cell of the
table.
9. In the right cell, click the blank area, and then press SHIFT+ENTER to create a new line.
10. Drag the ContentPlaceholder control onto the right cell of the table and position it under
the SiteMapPathcontrol.
When you are using a master page, you create the pages in your site as content pages. The content pages
useContent controls to define the text and controls that are displayed in the ContentPlaceHolder control
of the master page. Therefore, you will have to re-create the Home, Products, and Hardware pages as
content pages.
To create content pages for the site
1. In Solution Explorer, right-click the Home.aspx page, click Delete, and then click OK.
2. Repeat step 1 for the Products.aspx, Software.aspx, Training.aspx, and Hardware.aspx pages, and
any other pages you have created.
You will re-create the pages as content pages that use a master page.
3. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
4. In the Add New Item dialog box:
a. Under Visual Studio installed templates, click Web Form.
b. In the Name box, type Home.aspx.
c. Select the Select master page check box.
d. Click Add.
The Select a Master Page dialog box appears.
5. Under Contents of folder, click Navigation.master, and then click OK.
You have created a content page that is bound to the master page that you created in the
preceding section.
6. Switch to Design view.
In Design view, you see the layout that you created for the master page, with an editable region
corresponding to the ContentPlaceHolder1 control on the master page.
7. Click inside the Content window.
This is where you can add content for this specific page.
8. Type Home, and then format the text as Heading 1.
You have created the static text (specifically, the heading) for the Home page.
9. Repeat steps 3 through 8 to create a Products.aspx content page and a Hardware.aspx content
page. In step 8, type Products and Hardware, respectively, instead of Home.
Testing Navigation Controls in the Master Page
Testing with master pages and content pages is the same as testing individual pages.
To test navigation controls in the master page
1. Open the Products.aspx page, and then press CTRL+F5 to run the page.
The Products content page is merged with the master page. In the browser, you see a page that
contains the Products heading and the navigation controls that you added to the master page.
2. In the TreeView control, click Hardware.
The Hardware page is displayed with the same layout as the Products page, except that
the SiteMapPathcontrol displays a different path.
Next Steps
This walkthrough illustrates the basic functionality of ASP.NET site navigation and the navigation controls.
You might want to experiment with additional features of navigation. For example, you might want to do
the following:
 Format the SiteMapPath control to customize its appearance. The control supports many options
that manage how the links are displayed. For more information, see SiteMapPath.
 Customize the display of the pages in the TreeView control. For example, you might highlight the
current page in the tree view node.
 Work programmatically with the site-navigation information. A SiteMapPath control is available
on the current page, which you can use to programmatically display navigation information.
 Use a different data store for the site-map information. Instead of using the default XML site-map
file, you might want to use an existing site map or store site-map information in a database.
ASP.NET site navigation uses a provider model. You can create a component that manages site-
map information, and then configure your application to use that component instead of the
default site-map provider. For more information, seeASP.NET Site Navigation Providers.
Testing Web Pages in Visual
Studio
.NET Framework 4.5
Other Versions
Visual Studio provides you with various ways to test web pages as you are developing them. You have the
following choices:
 Start Debugging (F5). This option runs the web project in the browser and allows you to
perform debugging tasks such as stepping through code and stopping at breakpoints.
 Start Without Debugging (CTRL+F5). This option runs the web project in the browser without
using the debugger. It approximates the user experience.
 View in Browser (CTRL+SHIFT+W). This option runs a selected page in the browser. Debugging
breakpoints are not in effect even if debugging is enabled.
Browser Options
By default, Visual Studio uses your default browser to test pages. To use a different browser or Page
Inspector, right-click the page in Solution Explorer and then click either Browse With or View in Page
Inspector. The Browse Withlets you select a browser from a list, add new browsers to the list, or set one
as the default browser. (The default browser setting here applies only to the Visual Studio environment
and not to Windows.)
Build Options
By default, Visual Studio builds the web project when you run a page. Building the project helps you find
compile-time errors before the page is displayed in the browser. You can set options to specify whether
you want to build the entire project, the current page, or not build at all.
For more information, see Building (Compiling) Web Site Projects.
Running with a Startup Page
By default, when you run a web project, Visual Studio runs the page that is currently open. However, in
some cases you might always want to start your web project with a specific page. For example, your web
project might have a home page where users make a selection that is required for other pages in the site
or application. In this case, you can configure your web project to display that page first when you test run
your application.
To specify a start page, right-click the page in Solution Explorer and then click Set As Start Page.
Note
Setting a start page in Visual Studio affects only your testing. It does not set the start page for the
website when it is published. To specify a default page for your website, first use Internet
Information Services (IIS) Manager to enable a default document for your website or virtual
directory. Then, select the page that you want. For more information, see the topic Configuring
Default Documents in IIS 7.
Running on a Specific Web Server
When you run a page, Visual Studio launches the web server, launches the browser, and loads the
specified page into the browser. In effect, Visual Studio passes the URL of the current page to the web
server, and the web server runs the page that was requested.
The web server that is used to run the page depends on the type of website you are working with:
 For File system web projects, Visual Studio launches its own web server and runs the page locally.
However, you can also specify a start URL to use when testing a web page. This method is useful if
you want to test a file system website on another computer with IIS. For more information about
the ASP.NET Development Server, see Web Servers in Visual Studio for ASP.NET Web Projects.
 For local IIS Express, local IIS, and remote IIS sites, Visual Studio runs the page in the
corresponding instance of IIS or IIS Express. For more information, see Web Servers in Visual
Studio for ASP.NET Web Projects.
 For FTP-deployed websites, Visual Studio runs the page by using the start URL that you provide as
part of the FTP website properties. If you have not provided one, Visual Studio prompts you for
the start URL when it is required. For more information, see FTP-Deployed Web Site Projects.
For a remote website or FTP site, the remote computer must be running the same .NET Framework version
that you are developing for.
Running with the Debugger
Running your page with the debugger enables you to perform debugging tasks, such as stepping through
code and stopping at breakpoints. For more information, see ASP.NET Debugging Overview.
Running with the debugger requires the following:
 Configure the page or web project to enable debugging. This option compiles the page with extra
information (debugging symbols) that the debugger uses. Visual Studio checks to see if
debugging is enabled. If it is not, Visual Studio sets the compilation options in the local
Web.config file to include debugging, creating the Web.config file if necessary.
 Configure the web server with adequate permissions to allow the current user account to debug.
If you are debugging a page that is running under IIS, you must be an administrator on the
computer. If that is not practical, you can use IIS Express or the ASP.NET Development Server to
debug applications without special permissions. For details, see Web Servers in Visual Studio for
ASP.NET Web Projects and How to: Specify the Web Server for Web Projects in Visual Studio.
Note
Configure your pages or website to run without debugging before you deploy the site to a
production server. Debugging options add overhead to the page and can affect server
performance.
Testing a Page
You can test pages when you are developing web application projects or website projects in Visual Studio.
To test run a web page
 Perform one of the actions listed in the following table. All of the actions run the specified page in
the default browser.
To Do this
Run the current page or
startup page in the
debugger.
For information about the
startup page, see the
section How to: Specify a
Startup Page for a Web
On the Debug menu, click Start Debugging, or press F5.
If the page or the website has not previously been
configured to enable debugging, Visual Studio prompts you
to enable debugging. If you choose not to enable debugging,
the page runs in the default browser but does not allow you
to attach a debugger to it.
Site.
Note
Before you publish a website, disable debugging.
Debugging adds overhead to performance and could
display information to the user that you do not want to
reveal. For details, see How to: Enable Debugging for
ASP.NET Applications
Run the current page or
startup page without the
debugger.
For information about the
startup page, see the
section How to: Specify a
Startup Page for a Web
Site.
On the Debug menu, click Start Without Debugging, or
press CTRL+F5.
Run the current page in a
browser instance inside of
Visual Studio.
Right-click a blank area of the page and then click View in
Browser.
Note
The View in Browser command is not available for files
that do not render in a browser (such as the Web.config
file).
Testing with an Alternate Browser
When you run a page, Visual Studio invokes the default browser. You can also test a page by using an
alternate browser, as described in the following procedure.
To test a web page with an alternate browser
1. In Solution Explorer, right-click the page you that want to test and then click Browse With.
2. In the Browse With dialog box, select an alternate browser.
3. If the browser that you want to use is not listed, click Add, specify the alternate browser program,
and then click OK.
Note
You can set the alternate browser as the default browser for Visual Studio by clicking Set
as Default. This option sets the default browser only for testing web pages in the current
website. It does not affect the default browser setting in Windows.
4. When you have selected a browser, click Browse.
Setting Build Options for Testing a Page
Visual Studio can build the current page or the entire website when you run a page. Building helps you
find compile-time errors before the page appears in the browser. You can set options to specify whether
you want to build the entire site, the current page, or not build at all.
To specify build behavior when running a page in a website project
1. In Solution Explorer, right-click the name of the website that you want to run, and then
click Property Pages.
2. Click the Build tab.
3. In the Before running the startup page list, select the build option that you want before running
pages.
If you have configured the website to build before running a page, you can further specify what happens
if the page or website has errors.
To specify run behavior if build errors occur in a website or Web application
project
1. On the Tools menu, click Options.
2. Select the Show all settings check box if it is not already selected.
3. Expand the Projects and Solutions node, and then click Build and Run.
4. Under On Run, when build or deployment errors occur, select the option for behavior that you
want if the build process encounters an error.
How to: Specify Start Pages for Testing Web Sites in Visual
Studio
When you use Start Debugging or Start Without Debugging to run a web project, Visual Studio runs
the page that currently has the focus. However, you can set a start page to have your website or Web
application always begin with the same page. If you set a start page, the Start Debugging or Start
Without Debugging commands always run the page that you set, not the current page.
Setting a start page in Visual Studio affects only your testing. It does not set the start page for the web
project when it is published. To specify a default start page for a website, use Internet Information
Services (IIS) to enable a default document and specify the page. For more information, see Configuring
Default Documents in IIS 7.
Note
If you are working with a website for ASP.NET Web Pages (.cshtml files), use the procedure for
website projects.
To specify a start page for testing a web application project in Visual Studio
1. In Solution Explorer, under the Web application name, double-click the Properties folder.
-or-
In Solution Explorer, right click the Web application name, and then from the shortcut menu,
chooseProperties.
2. On the Web tab, in the Start Action section, choose Specific Page.
3. Type the name of the file of the start page.
-or-
 In Solution Explorer, right-click the page that you want to specify as the start page, and then
click Set As Start Page.
To specify a start page for testing a website project in Visual Studio
1. In Solution Explorer, right-click the name of the website for which you want to specify the start
page, and then click Property Pages.
2. In the Start Options tab, select the Specific page check box and then type or browse to the
name of the start page.
-or-
 In Solution Explorer, right-click the page that you want to specify as the start page, and then
click Set As Start Page .
Walkthrough: Creating a Web
Site with Membership and User
Login
Other Versions
A typical requirement for Web sites is to allow only some users (authenticated users) to see certain pages.
In that case, it is typical for the Web site to provide a way for users to log in and be authenticated, and to
hide information from anonymous users (users who are not logged in).
Note
If you create a web application in Visual Studio using a Web project template, the template
includes pages that implement basic login functionality using login controls and ASP.NET
membership. However, the template does not include all the functionality that is described in this
walkthrough. If the template does not include the functionality you want, or if you prefer to
create the membership system yourself, you can use the same ASP.NET controls that are in the
template to create custom login and membership pages.
This walkthrough shows you how to manually put together these ASP.NET controls and
ASP.NET membership services to create an application that authenticates users and that hides
information from anonymous users. For information about how to use the Web site project
templates, see Walkthrough: Creating an ASP.NET Web Site with Basic User Login.
Tasks illustrated in this walkthrough include the following:
 Creating a Web site.
 Creating a home page that is accessible to all users.
 Creating a login page.
 Creating a members-only page.
 Configuring membership.
 Adding new users (members).
 Letting users change their password.
 Letting users reset a forgotten password.
Prerequisites
In order to complete this walkthrough, you will need the following:
 Visual Studio or Visual Web Developer Express installed on your computer.
 SQL Server Express installed locally on your computer.
 Access to an email server that can forward email messages. (The server does not have to be able
to receive messages.) If you do not have access to an email server, you can run the procedures in
this walkthrough, but you will not be able to use the password-recovery feature.
Creating the Web Site
To create custom user login pages, you will first create an empty Web site.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a Web site
1. Start Visual Studio or Visual Web Developer Express.
2. On the File menu, click New Web Site. (If you do not see this option, click New, and then
click Web Site.)
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Empty Web
Site.
You are selecting an Empty Web Site template because you will add membership and login
capability by hand rather than using the features built into the other templates.
4. In the Web location list box, select File System and enter the name of the folder where you want
to keep the pages of the Web site. For example, enter the folder
name C:WebsitesMembership and then click OK.
Visual Studio creates an empty Web site that contains only a Web.config file.
Creating the Home Page
You will first create the home page where all users of the Web site will start.
To create a home page
1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item.
The Add New Item dialog box is displayed.
2. If you do not see the Solution Explorer window, select the View menu and then click Solution
Explorer.
3. Select Web Form, accept the default name (Default.aspx), and then click Add.
4. Switch to Design view and add text such as My Home Page.
5. In the Formatting toolbar, use the Block Format drop-down list to format the text as Heading 1.
Creating the Login Page
As part of your Web site, you must establish the user's identity (authenticate the user) so that the Web
site can perform actions based on who the user is, such as showing or hiding information. To get the
user's identity, you must have the user log in. Therefore, your Web site must include a login page.
To create a login page
1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item.
2. Select Web Form, change the default name to Login.aspx, and then click Add.
Note
For this walkthrough, the page must be named Login.aspx. By default, ASP.NET
authentication is configured to work with a page that has this name. (Although you will
not do so in this walkthrough, you can change the default login page in the Web.config
file.)
3. In the Login.aspx page, switch to Design view.
4. Add text such as Login Page to the page and again use Block Format to format the title
as Heading 1.
5. Press ENTER to create a new paragraph.
6. From the Login group of the Toolbox, drag a Login control to the new paragraph.
The Login control is a single control that will prompt the user for credentials and validate them. If
you want, you can use the Auto Format link on the smart tag panel to apply formatting to
the Login control.
Displaying Detailed Login Errors
The Login control includes validation to help users enter correct information. For example, if a user skips
the password, a validator control displays an asterisk (*) next to the Password text box. To provide more
detail about errors in the page, you will add a ValidationSummary control.
To display detailed login errors
1. From the Validation group of the Toolbox, drag a ValidationSummary control onto the
Login.aspx page. Drop the ValidationSummary under the Login control.
2. In the Properties window for the ValidationSummary control, set the ValidationGroup property
to Login1, which is the ID of the Login control that you added previously.
(If you do not see the Properties window, from the View Menu, click Properties Window.)
3. Save the page and close it.
You can now test the login page.
To test the login page
1. In Solution Explorer, right-click the Login.aspx page and select View in Browser.
2. Without entering anything into the login control, click Log In.
An asterisk is displayed next to the User Name box and next to the Password box, because you
did not enter values for these values. In addition, the ValidationSummary control displays error
messages that provide details about the errors on the page.
3. Close the browser.
Displaying Information for Logged-In Users
The next step is to modify the home page to customize the display depending on whether the user is
logged in. Anonymous users will see a generic message that invites them to log in. Logged-in users will
see a message that welcomes them by their user name.
To customize the display for logged-in users
1. Switch to or open the Default.aspx page and switch to Design view.
2. From the Login group of the Toolbox, drag a LoginView control onto the page.
The LoginView control is displayed with its AnonymousTemplate template open. This template
allows you to define the content that users will see before they log in.
3. Click the edit area of the LoginView control to activate editing.
4. In the edit area of the LoginView control's AnonymousTemplate template, enter You are not
logged in. Click the Login link to sign in..
The following illustration shows the LoginView control edit area that contains the text.
It might be easier to copy the text and paste it into the edit area or add the text as markup
in Source view than entering the text directly into the edit area. The following example shows
how the text appears in markup.
<asp:LoginView ID="LoginView1" runat="server" >
<AnonymousTemplate>
You are not logged in. Click the Login link to sign in.
</AnonymousTemplate>
</asp:LoginView>
5. In Design view, select the LoginView control, and then on the LoginView Tasks panel, in
the Views list, clickLoggedInTemplate. If you do not see the LoginView Tasks panel, right-click
the heading of the LoginViewcontrol and then click Show Smart Tag.
The LoggedInTemplate defines the content that will be displayed to users who have logged in.
6. Click the edit area of the LoginView control to activate editing and then enter the following
text: You are logged in. Welcome,
7. Place the cursor in the edit area of the LoggedInTemplate after the text you just added. From
the Login group of the Toolbox, double-click the LoginName control. The LoginName control
displays the name of the user who is logged in.
8. From the Login group of the Toolbox, drag a LoginStatus control into the page.
The LoginStatus control displays a Login link when the user is not logged in. When the user is
logged in, the control displays a Logout hyperlink.
9. Save the page.
Creating the Members-Only Page
A typical task in many Web sites is to allow only logged-in users to view certain pages. Therefore, the next
task for this walkthrough is to create a folder for members-only pages, add a page to it, and then create a
rule that limits access to pages in the folder.
To add a new folder to the Web site
1. In Solution Explorer, right-click the name of the Web site and then click New Folder.
2. Name the folder MemberPages.
3. In Solution Explorer, right-click the MemberPages folder and then click Add New Item.
4. Add a new Web Forms page named Members.aspx.
5. Click Add.
Note
Make sure that you create the page in the MemberPages folder.
6. Switch to Design view and add text to the page, such as Welcome to the members-only
page. The exact text is not important, as long as you will be able to recognize this page when you
see it in the browser. Use theBlock Format drop-down list to format the text as Heading 1.
You can now add a hyperlink to the home page that sends users to the members-only page. In a real
application, you would probably put the members-only page link in the logged-in template of
the LoginView control. That way, visitors to your site would not see the link until they are logged in.
However, for this walkthrough, you will make the link available to all users so that you can see the effect
of trying to view a members-only page without first logging in.
To link to the members-only page
1. Open or switch to open the Default.aspx page.
2. From the Standard group of the Toolbox, drag a HyperLink control onto the page.
3. In the Properties window for the HyperLink control, do the following:
a. Set the Text property to Members-only page.
b. Set the NavigateUrl property to ~/MemberPages/Members.aspx. This points to the
page that you created previously.
4. Save the page.
You can now test the hyperlink you just added to the home page.
To test the link
1. In Solution Explorer, right-click the Default.aspx page and then click View in Browser.
2. Click Members-only page.
The members-only page is displayed, because it is not protected yet. (Moreover, by default,
ASP.NET uses Windows authentication, so it considers you logged in under your Windows
credentials.)
3. Close the browser.
Configuring Membership
The next step is to configure ASP.NET membership and set up users. To do this, you can use the Web Site
Administration Tool, which provides a wizard-like interface for making configuration settings. When you
complete the configuration, a SQL Server database named ASPNETDB.MDF is created in the App_Data
folder of the project. The database contains membership information for this Web site.
For this walkthrough, you will define a single user.
To create a membership user
1. On the Website menu, click ASP.NET Configuration.
2. Select the Security tab, click the Use the security Setup Wizard to configure security step by
step link, and then click Next.
The wizard displays a page where you can select the authentication method that your Web site
will use.
3. Select the From the Internet option.
This option specifies that your Web site will use ASP.NET forms authentication, which relies on the
ASP.NET membership system. When you use forms authentication, users log in to the Web site by
using the login page that you created earlier in this walkthrough. (The From a local area
network option configures the Web site to use Windows authentication, which is practical if your
site is accessed only by people who are on a corporate network. As noted earlier, this is the
default setting for ASP.NET membership.)
4. Click Next.
The wizard indicates that the application is configured to use advanced provider settings. By
default, membership information is stored in a Microsoft SQL Server database file in the App_Data
folder of your Web site.
5. Click Next.
6. Clear the Enable roles for this Web site check box, and then click Next.
The wizard displays a page where you can create new users.
7. Enter information that defines a user of your Web site. Use the following values as guidelines.
(You can use any values that you want, but be sure to note your entries. You will use these entries
later in the walkthrough.)
o User Name Your name (without spaces), or a sample name.
o Password A password. A strong password is required (one that includes uppercase and
lowercase letters, punctuation, and that is at least eight characters long).
o E-mail Your personal email address. If you have to reset your password, this email
address will be used to send you a new password. Therefore, you need to enter a valid
email address.
o Security Question and Security Answer Enter a question and answer that can be used
later if you need to reset your password.
8. Select the Active User check box.
9. Click Create User.
The wizard displays a confirmation page.
Note
Leave the Web Site Administration tool open.
Setting Up Access Rules for the Members Page
Earlier in the walkthrough, you created a folder named MemberPages and added a members-only page.
In this part of the walkthrough, you will create a rule that makes sure that only logged-in users can access
pages in that folder.
To set up access rules
1. In the security wizard in the Web Site Administration Tool, click Next.
The wizard displays the Add New Access Rules page.
2. In the Add New Access Rule box, expand the node for your Web site.
3. Select MemberPages, the folder that you created earlier.
4. Under Rule applies to, select Anonymous Users.
5. Under Permission, select Deny.
The rule you are creating denies access to anonymous users — that is, users who have not logged
in.
6. Click Add This Rule.
The new rule is displayed in the grid. When users request a page from the MemberPages folder,
the rules are checked to determine whether the user is allowed access to the page.
7. Click Finish.
You are now done with the wizard. The wizard closes and you are returned to the Security tab of the Web
Site Administration Tool.
Testing the Members-Only Page
You can test the members-only page by accessing it as an anonymous user or as a logged-in user.
To test the members-only page
1. In Visual Studio, switch to the Default.aspx page and press CTRL+F5 to run the Web site.
2. When the Default.aspx page is displayed in the browser, do not log in. Instead, click
the Members-only page link.
The Login.aspx page is displayed, because access to the member’s page is denied for anonymous
users.
3. On the login page, enter the user name and password that you used earlier to create the user to
log in.
When you log in, the site redirects you to the members-only page, because you are no longer an
anonymous user.
4. Close the browser window.
Adding New Users
Earlier in the walkthrough, you created a user by using the Web Site Administration Tool. The Web Site
Administration Tool is useful if you are working with a small, defined list of users, such as creating users
for a small team. However, in many Web sites, users can register themselves. To support this feature,
ASP.NET includes theCreateUserWizard control that performs the same task you performed earlier by
using the Web Site Administration Tool.
Creating a Registration Page
In this part of the walkthrough, you will add a functionality that allows users to register on your Web site.
You will start by creating a registration page.
To create a registration page
1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item.
2. Add a new Web Form named Register.aspx and click Add.
Note
Make sure that you create the page in the root of the Web site, not in the MemberPages
folder.
3. In the Register.aspx page, switch to Design view and enter text such as Register into the page. In
theFormatting toolbar, use the Block Format drop-down list to format the text as Heading 1.
4. From the Login group of the Toolbox, drag a CreateUserWizard control onto the page.
5. In the Properties window for the CreateUserWizard control, set
the ContinueDestinationPageUrl property to~/Default.aspx.
This configures the control so that when users click Continue after they create a user, they are
returned to the home page.
6. From the Standard group of the Toolbox, drag a HyperLink control onto the page.
7. In the Properties window for the HyperLink control, do the following:
o Set the Text property to Home.
o Set the NavigateUrl property to ~/Default.aspx.
8. Save and close the page.
You will now add a link that displays the registration page to both the home page and the Login page. For
this walkthrough, assume that you want to display the registration link only to users who are not logged
in.
To create a registration link on the home page
1. Switch to or open the Default.aspx page.
2. Right-click the LoginView control that you added previously, and then click Show Smart Tag.
3. In the LoginView Tasks panel, select AnonymousTemplate from the Views list in order to
activate editing in the anonymous template.
4. From the Standard group of the Toolbox, drag a HyperLink control into the anonymous
template. It might be easier to put the cursor in the editing area and double-click
the HyperLink control in the Toolbox.
5. In the Properties window for the HyperLink control, do the following:
a. Set the Text property to Register.
b. Set the NavigateUrl property to Register.aspx.
6. Switch to or open the Login.aspx page.
7. From the Standard group of the Toolbox, drag a HyperLinkcontrol into the page.
8. In the Properties window for the HyperLinkcontrol, do the following:
a. Set the Text property to Register.
b. Set the NavigateUrl property to Register.aspx.
You can now test the registration process.
To test registration
1. Switch to the Default.aspx page and press CTRL+F5 to run the Web site and display the
Default.aspx page.
Because you are not logged in, the Register link is displayed.
2. Click the Register link. The registration page is displayed.
3. In the boxes, enter a new user name, a strong password, an email address, and a security question
and answer. (All the pieces of information are required.)
4. Click Create User. A confirmation message is displayed.
5. Click Continue.
You are returned to the home page as a logged-in user. Note that the Login link has changed
to Logoutand that the information displayed in the Login control is from
the LoggedInTemplate property, not from the AnonymousTemplate property.
6. Click the Logout link.The page changes to display the information for anonymous users.
7. Click the Login link.
8. Enter the credentials for the user you just created.You are logged in as the new user.
9. Close the browser window.
Letting Users Change Their Password
Users sometimes want to change their passwords, and it is often impractical to perform this task by hand.
You can use another ASP.NET control to let users change passwords on their own. To change a password,
users must know their existing password.
You will add a page where logged-in users can change their password.
To create a password-change page
1. In Solution Explorer, right-click the MemberPages folder, click Add New Item, add a new Web
Form, name itChangePassword.aspx and then click Add.
Make sure that you create the page in the MemberPages folder. You are putting the page in the
MemberPages folder because only logged-in users can change their passwords.
2. In the ChangePassword.aspx page, switch to Design view and enter text such as Change
Password and format it using Heading 1.
3. From the Login group of the Toolbox, drag a ChangePassword control onto the page.
4. In the Properties window for the ChangePassword control, set
the ContinueDestinationPageUrl property to~/Default.aspx.
This configures the control so that when users click Continue after they change a password, they
are redirected to the home page.
5. Save and close the page.
Creating a Password-Change Link on the Home Page
You can now add a link to the home page that displays the ChangePassword.aspx page. You will make the
link available only to users who are logged in.
To create a password-change link on the home page
1. Switch to or open the Default.aspx page.
2. Right-click the LoginView control and then click Show Smart Tag.
3. In the LoginView Tasks pane, in the Views list, click LoggedInTemplate.
This switches the LoginView control to edit mode for the content that will be displayed to users
who are logged in.
4. From the Standard group of the Toolbox, drag a HyperLink control into the editing region.
5. In the Properties window for the HyperLink control, do the following:
a. Set the Text property to Change password.
b. Set the NavigateUrl property to ~/MemberPages/ChangePassword.aspx.
Testing the Password-Change Page
You can now test the password-change process.
To test the password-change page
1. Press CTRL+F5 to run the Web site.
2. In the Default.aspx, page, click the Login link and log in as one of the users you have created.
When you are finished, you are returned to the home page as a logged-in user.
3. Click the Change password link.
4. In the password-change page, enter the old password and a new password, and then
click Change Password.
5. Click Continue.
6. On the home page, click Logout.
7. Click Login.
8. Log in with the new password.
9. Close the browser.
Letting Users Reset Their Password
When users forget their password, the Web site can enable them to recover or reset their password. The
password can be recovered (that is, sent to the user) if the password is not hashed.
When a password is hashed, the membership system does not store the actual password. Instead, the
system processes the password using a one-way algorithm (a hashing algorithm) that produces a unique
value for the password, and then stores this hash value. This algorithm can be repeated to test a user's
password at login, but cannot be reversed to produce the actual password. This increases the security of
the membership database, because getting access to the database does not mean that passwords are
exposed.
By default, the membership provider stores the password as a hash value. Therefore, the password cannot
be recovered. Instead, if a user has forgotten a password, the Web site must generate a new password
and send it to the user in email. For your Web site to send email messages your computer must have
access to a Simple Mail Transport Protocol (SMTP) server.
In this procedure, you will add a password-reset page to your Web site and configure the Web site to
send users a new password by email. To reset a password, a user must provide a user name and must
answer the security question that was provided when the user registered. The new password is sent to the
email address that the user provided when registering.
To create the password-reset page
1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item.
2. Add a new Web Form page, name it PasswordRecovery.aspx and click Add.
Note
Make sure that you create the page in the root of the Web site, not in the MemberPages
folder.
3. In the PasswordRecovery.aspx page, switch to Design view and enter text such as Forgot
Password into the page and format it as Heading 1.
4. From the Login group of the Toolbox, drag a PasswordRecovery control onto the page.
5. Open or switch to the Login.aspx page and switch to Design view.
6. From the Standard group of the Toolbox, drag a HyperLink control onto the page.
7. Set the Text property to Forgot password and the NavigateUrl property
to ~/PasswordRecovery.aspx.
Configuring the Web site to Use an SMTP Server
Next, you will configure your Web site to use an SMTP server. To configure the server correctly, you must
have the setup information. If the server requires authentication, you will need the user name and
password. For information about how to obtain this setup information, contact the system administrator.
After you have determined how to access the SMTP server, you must configure your Web site to route
email messages to that server. You can do so in the Web Site Administration Tool or by making an entry
in your Web site's Web.config file, which contains a series of settings that determine how your application
runs. The following procedure shows how to use the ASP.NET Web Site Administration Tool to perform
this task.
To configure the Web site to use an SMTP server
1. On the Website menu, click ASP.NET Configuration.
2. In the Web Site Administration Tool, click the Application tab.
3. Under SMTP Settings, click Configure SMTP email settings. The tool displays a page where you
can configure email.
4. Enter the information that the page prompts you for.
5. Click Save, and in the confirmation page, click OK.
The Web Site Administration Tool creates a Web.config file that has the settings that you have
made in themailSettings section.
6. Close the browser window in which the Web Site Administration tool is displayed.
7. Open the Web.config file.
8. Under the system.net element and under the mailSettings element, verify
your smtp and host settings.
Note
If your SMTP server requires a secure connection, you must set the enableSsl attribute
to true. You do this in the network section of the smtp element in the Web.config file.
9. The SMTP settings in the Web.config file will resemble the following example.
10. <system.net>
11. <mailSettings>
12. <smtp from="joe@contoso.com">
13. <network host="<server>" password="<password>"
14. userName="joe@contoso.com" enableSsl="true" />
15. </smtp>
16. </mailSettings>
17. </system.net>
Security Note
To protect configuration information like the user name and password, you can have
ASP.NET encrypt the portion of the Web.config file where the SMTP information is
stored. For more information, seeEncrypting Configuration Information Using Protected
Configuration. In addition, by default ASP.NET sends the smtp server credentials in
clear text and can be intercepted by programs that record network activity. For a
production site, you should use the SSL (secure sockets layer) to encrypt sensitive
information that is exchanged with the server.
Testing Password Reset
You can now test the process of resetting your password. You will then use the new password to log in.
To test the password-reset page
1. Press CTRL+F5 to run the Web site.
2. Click Login.
3. In the Login page, click the Forgot password link. Enter your user name and then click Submit.
4. Enter the answer to the security question and then click Submit.
5. Wait for a few minutes and then check your email.
6. Use the new password to log in.

More Related Content

What's hot (20)

PPTX
Dreamweaver
Jacqueline Wanner
 
PDF
Dreamweaver cs6 step by step
zoran Jelinek
 
PDF
Joomla Quick Start 1
guest38bfe1
 
PPTX
Start a Blog: Module 6
Merri Dennis
 
PPTX
How to Use Dreamweaver cs6
Salman Memon
 
PDF
Joomla Template Tutorial
brighteyes
 
PDF
Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004
brighteyes
 
PDF
Oracle EMC 12C Grand Tour
Rakesh Gujjarlapudi
 
PPTX
Unit a adobe dreamweaver cs6
Krista Lawrence
 
PPT
Illustrated introductory DreamWeaver
Ashish Srivastava
 
PPTX
Dreaweaver cs5
Miguel Kerlegan
 
PPT
Getting Started with Iron Speed Designer
Iron Speed
 
PDF
Fewd week7 slides
William Myers
 
PPT
An Introduction To Pbworks
choikwokto
 
PDF
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 
PPTX
Dreamweawer
aditi sharma
 
PDF
Fewd week8 slides
William Myers
 
PDF
INTRODUCTION TO VISUAL BASICS
Prof Ansari
 
PPTX
Understanding IDEs
sunmitraeducation
 
PDF
Build your first rpa bot using IBM RPA automation
Winton Winton
 
Dreamweaver
Jacqueline Wanner
 
Dreamweaver cs6 step by step
zoran Jelinek
 
Joomla Quick Start 1
guest38bfe1
 
Start a Blog: Module 6
Merri Dennis
 
How to Use Dreamweaver cs6
Salman Memon
 
Joomla Template Tutorial
brighteyes
 
Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004
brighteyes
 
Oracle EMC 12C Grand Tour
Rakesh Gujjarlapudi
 
Unit a adobe dreamweaver cs6
Krista Lawrence
 
Illustrated introductory DreamWeaver
Ashish Srivastava
 
Dreaweaver cs5
Miguel Kerlegan
 
Getting Started with Iron Speed Designer
Iron Speed
 
Fewd week7 slides
William Myers
 
An Introduction To Pbworks
choikwokto
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Sean Burgess
 
Dreamweawer
aditi sharma
 
Fewd week8 slides
William Myers
 
INTRODUCTION TO VISUAL BASICS
Prof Ansari
 
Understanding IDEs
sunmitraeducation
 
Build your first rpa bot using IBM RPA automation
Winton Winton
 

Viewers also liked (13)

DOCX
Android examples
Aravindharamanan S
 
PDF
Sq lite manager
Aravindharamanan S
 
PDF
00016335
Aravindharamanan S
 
DOCX
Tutorial 1
Aravindharamanan S
 
PDF
Schemas and soap_prt
Aravindharamanan S
 
PDF
Cdn tutorial adcom
Aravindharamanan S
 
PDF
Jaxrs 1.0-final-spec
Aravindharamanan S
 
PDF
Dynamically define rad grid using code behind in c# grid - ui for asp
Aravindharamanan S
 
PDF
sample tutorial
Aravindharamanan S
 
PDF
Create link button in radgrid dynamically without item template tags in aspx ...
Aravindharamanan S
 
PDF
Radgrid
Aravindharamanan S
 
PDF
Android tutorial
Aravindharamanan S
 
Android examples
Aravindharamanan S
 
Sq lite manager
Aravindharamanan S
 
Tutorial 1
Aravindharamanan S
 
Schemas and soap_prt
Aravindharamanan S
 
Cdn tutorial adcom
Aravindharamanan S
 
Jaxrs 1.0-final-spec
Aravindharamanan S
 
Dynamically define rad grid using code behind in c# grid - ui for asp
Aravindharamanan S
 
sample tutorial
Aravindharamanan S
 
Create link button in radgrid dynamically without item template tags in aspx ...
Aravindharamanan S
 
Android tutorial
Aravindharamanan S
 
Ad

Similar to Walkthrough asp.net (20)

PPSX
A comprehensive software infrastructure of .Net
Prognoz Technologies Pvt. Ltd.
 
PPSX
01 asp.net session01
Vivek Singh Chandel
 
PPTX
Lecture slides_Introduction to ASP.NET presentation
ssuserbf6ebe
 
PDF
Asp.net w3schools
Arjun Shanka
 
PPT
.Net Framework Overview. Fundamentals of .Net Framework
pavankumar47666
 
PPS
01 asp.net session01
Mani Chaubey
 
DOCX
Asp notes
hello232
 
PPTX
Vb.net ide
Faisal Aziz
 
PPT
Asp.net architecture
Iblesoft
 
PPT
2310 b 02
Krazy Koder
 
PPT
Introduction to ASP.net. It provides basic introduction
ssuserbf6ebe
 
PPT
introaspnetkjadbfksdjkfaskjdbfkajsbfkjfjkswa.ppt
AvijitChaudhuri3
 
PPT
introaspnet.ppt
asmachehbi
 
PPT
introaspnet.ppt
IbrahimBurhan6
 
PPSX
Introduction of VS2012 IDE and ASP.NET Controls
KhademulBasher
 
PPT
Aspintro
ambar chakraborty
 
PPT
Introaspnet
Nagaraju Yajjuvarapu
 
PPTX
10. building forms
Pramod Rathore
 
PPT
This is the introduction to Asp.Net Using C# Introduction Variables State Man...
sagar490070
 
A comprehensive software infrastructure of .Net
Prognoz Technologies Pvt. Ltd.
 
01 asp.net session01
Vivek Singh Chandel
 
Lecture slides_Introduction to ASP.NET presentation
ssuserbf6ebe
 
Asp.net w3schools
Arjun Shanka
 
.Net Framework Overview. Fundamentals of .Net Framework
pavankumar47666
 
01 asp.net session01
Mani Chaubey
 
Asp notes
hello232
 
Vb.net ide
Faisal Aziz
 
Asp.net architecture
Iblesoft
 
2310 b 02
Krazy Koder
 
Introduction to ASP.net. It provides basic introduction
ssuserbf6ebe
 
introaspnetkjadbfksdjkfaskjdbfkajsbfkjfjkswa.ppt
AvijitChaudhuri3
 
introaspnet.ppt
asmachehbi
 
introaspnet.ppt
IbrahimBurhan6
 
Introduction of VS2012 IDE and ASP.NET Controls
KhademulBasher
 
10. building forms
Pramod Rathore
 
This is the introduction to Asp.Net Using C# Introduction Variables State Man...
sagar490070
 
Ad

Recently uploaded (20)

PDF
Smart Steps to Choose the Right Career Path After 12th or Graduation
Reeshna Prajeesh
 
DOCX
Yeh Rishta Kya Kehlata Hai Upcoming Story.docx
aliraza904620
 
PPTX
Matter_in_Our_Surroundings_Lesson_Plan.pptx
devendrabele16
 
PDF
Buy Twitter Accounts_ Boost Your Brand and Reach in 2025 - Copy - Copy.pdf
Buy Old Twitter Accounts-100% Secure Aged With Followers
 
PPTX
ASHISH SINGH New PPT (1).pptxASHISH SINGH New PPT (1).pptxASHISH SINGH New PP...
ShivanshPratapSingh5
 
DOCX
PMCF -Performance Monitoring and Coaching Form
ROSALIESOMBILON
 
PPTX
A Guide for a Winning Interview July 2025
Bruce Bennett
 
PPTX
carbohydrates-230715125628-fbb297d6.pptx
pankajkushwah29
 
PDF
NotificationForTheTeachingPositionsAdvt012025.pdf
sunitsaathi
 
PPTX
Chemistry-Presentation-The-World-of-Silicates.pptx
swethasejal123
 
PDF
Your Growth in IT Starts Here – Powered by Formwalaa.in
Reeshna Prajeesh
 
PPTX
Plant Growth and Development-Part I, ppt.pptx
7300511143
 
PDF
Carolina Guerreno- Financial Leadership for a Sustainable Future.pdf
Carolina Guerreno
 
PPTX
Mastering the Cloud with AWS: A Deep Dive into Amazon Web Services
cbitssnavjotdm
 
PDF
Biography and career history of Neil Druker
Neil Druker
 
PDF
Why Agentops requires an artificial Intelligence developer.pdf
ssiddhant550
 
PPTX
Resume-Writing-Workshop powerpoint Presentation
nmorales22
 
PDF
Certificate PMP kamel_rodrigue_adda_1879235
kamelard
 
DOCX
PMCF (Performance Monitoring and Coaching Form
ROSALIESOMBILON
 
PDF
2025 - KPT - The best people are those you can't buy - Beata Mosór.pdf
bmosor
 
Smart Steps to Choose the Right Career Path After 12th or Graduation
Reeshna Prajeesh
 
Yeh Rishta Kya Kehlata Hai Upcoming Story.docx
aliraza904620
 
Matter_in_Our_Surroundings_Lesson_Plan.pptx
devendrabele16
 
Buy Twitter Accounts_ Boost Your Brand and Reach in 2025 - Copy - Copy.pdf
Buy Old Twitter Accounts-100% Secure Aged With Followers
 
ASHISH SINGH New PPT (1).pptxASHISH SINGH New PPT (1).pptxASHISH SINGH New PP...
ShivanshPratapSingh5
 
PMCF -Performance Monitoring and Coaching Form
ROSALIESOMBILON
 
A Guide for a Winning Interview July 2025
Bruce Bennett
 
carbohydrates-230715125628-fbb297d6.pptx
pankajkushwah29
 
NotificationForTheTeachingPositionsAdvt012025.pdf
sunitsaathi
 
Chemistry-Presentation-The-World-of-Silicates.pptx
swethasejal123
 
Your Growth in IT Starts Here – Powered by Formwalaa.in
Reeshna Prajeesh
 
Plant Growth and Development-Part I, ppt.pptx
7300511143
 
Carolina Guerreno- Financial Leadership for a Sustainable Future.pdf
Carolina Guerreno
 
Mastering the Cloud with AWS: A Deep Dive into Amazon Web Services
cbitssnavjotdm
 
Biography and career history of Neil Druker
Neil Druker
 
Why Agentops requires an artificial Intelligence developer.pdf
ssiddhant550
 
Resume-Writing-Workshop powerpoint Presentation
nmorales22
 
Certificate PMP kamel_rodrigue_adda_1879235
kamelard
 
PMCF (Performance Monitoring and Coaching Form
ROSALIESOMBILON
 
2025 - KPT - The best people are those you can't buy - Beata Mosór.pdf
bmosor
 

Walkthrough asp.net

  • 1. Walkthrough: Creating a Basic Web Forms Page in Visual Studio Other Versions This walkthrough provides you with an introduction to the Web development environment in Visual Studio and in Visual Web Developer Express for ASP.NET Web Forms pages. This walkthrough guides you through creating a simple ASP.NET Web Forms page and illustrates the basic techniques of creating a new page, adding controls, and writing code. Note This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages. Tasks illustrated in this walkthrough include:  Creating a file system Web site project.  Familiarizing yourself with Visual Studio.  Creating a single-file ASP.NET Web Forms page.  Adding controls.  Adding event handlers.  Running pages by using the Web server that is built into Visual Studio for testing. Prerequisites In order to complete this walkthrough, you will need:  Visual Studio or Visual Web Developer Express. For download information, see the Visual Studio Development Center Web site. Note If you are using Visual Studio, this walkthrough assumes that you selected the Web Developmentcollection of settings the first time that you started Visual Studio. For more
  • 2. information, see How to: Select Web Development Environment Settings.  The .NET Framework, which is installed when you install Visual Studio or Visual Web Developer Express. Creating a Web Site Project and a Web Forms Page In this part of the walkthrough, you will create a Web site project and add a new page to it. You will also add HTML text and run the page in your Web browser. For this walkthrough, you will create a file system Web site project that does not require that you work with Microsoft Internet Information Services (IIS). Instead, you will create and run your page in the local file system. A file system Web site project is one that stores pages and other files in a folder that you choose somewhere on your computer. Other Web project options include the following:  A local IIS Web site project, which stores your files in a subfolder of the local IIS root (typically, inetpubwwwroot).  An FTP site project, which stores files on a remote server that you gain access to across the Internet by using File Transfer Protocol (FTP).  A remote IIS Web site project, which stores files on a remote server that you can access across a local network.  A Web application project, which is similar to a file system Web site project except you compile it before deployment and deploy it as a dynamic link library (.dll) file. For more information about the difference between Web site projects and Web application projects, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Studio or Microsoft Visual Web Developer Express. 2. On the File menu, click New Web Site. The New Web Site dialog box appears, as shown in the following illustration:
  • 3. 3. Under Installed Templates, click Visual Basic or C# and then select ASP.NET Web Site. When you create a Web site project, you specify a template. Each template creates a Web project that contains different files and folders. In this walkthrough, you are creating a Web site based on the ASP.NET Web Sitetemplate, which creates files and folders that are typically used in ASP.NET Web sites. 4. In the Web Location box, select File System, and then enter the name of the folder where you want to keep the pages of your Web site. For example, type the folder name C:BasicWebSite. 5. Click OK. Visual Studio creates a Web project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). When a new page is created, by default Visual Studio displays the page in Source view, where you can see the page's HTML elements. The following illustration shows what you would see in Source view if you created a new Web page named FirstWebPage.aspx. A Tour of the Visual Studio Web Development Environment Before you proceed with working on the page, it is useful to familiarize yourself with the Visual Studio development environment. The following illustration shows you the windows and tools that are available in Visual Studio and Microsoft Visual Web Developer Express.
  • 4. Note This diagram shows default windows and window locations. The View menu allows you to display additional windows, and to rearrange and resize windows to suit your preferences. If changes have already been made to the window arrangement, what you see will not match the illustration. The Visual Studio environment To familiarize yourself with the Web designer  Examine the preceding illustration and match the text to the following list, which describes the most commonly used windows and tools. (Not all windows and tools that you see are listed here, only those marked in the preceding illustration.) o Toolbars. Provide commands for formatting text, finding text, and so on. Some toolbars are available only when you are working in Design view. o Solution Explorer window. Displays the files and folders in your Web site. o Document window. Displays the documents you are working on in tabbed windows. You can switch between documents by clicking tabs. o Properties window. Allows you to change settings for the page, HTML elements, controls, and other objects. o View tabs. Present you with different views of the same document. Design view is a near- WYSIWYG editing surface. Source view is the HTML editor for the page. Split view displays both the Designview and the Source view for the document. You will work with the Design and Source views later in this walkthrough. If you prefer to open Web pages in Design view, on the Tools menu, click Options, select the HTML Designer node, and change the Start Pages In option. o ToolBox. Provides controls and HTML elements that you can drag onto your page. Toolboxelements are grouped by common function.
  • 5. o Server Explorer/Database Explorer. Displays database connections. If Server Explorer is not visible, on the View menu, click Server Explorer or Database Explorer. Note The Server Explorer window is named Database Explorer in Microsoft Visual Web Developer Express. To see all available menu items in Microsoft Visual Web Developer Express, on the Toolsmenu, click Settings, and then click Expert Settings. Creating a New ASP.NET Web Forms Page When you create a new Web site using the ASP.NET Web Site project template, Visual Studio adds an ASP.NET Web Forms page named Default.aspx. You can use the Default.aspx page as the home page for your Web site. However, for this walkthrough, you will create and work with a new page. To add a page to the Web site 1. Close the Default.aspx page. To do this, right-click the tab that displays the file name and then click Close. 2. In Solution Explorer, right-click the Web site (for example, C:BasicWebSite), and then click Add New Item. The Add New Item dialog box is displayed. The following illustration shows an example of the Add New Item dialog box. 3. In the template list, select Web Form. 4. In the Name box, type FirstWebPage.
  • 6. When you created the Web site project, you specified a default language based on the project template that you selected. However, each time you create a new page or component for your Web site, you can select the programming language for that page or component. You can use different programming languages in the same Web site. 5. Clear the Place code in separate file check box. In this walkthrough, you are creating a single-file Web Forms page with the code and HTML in the same page. The code for ASP.NET Web Forms pages can be located either in the page or in a separate class file. 6. Click Add. Visual Studio creates the new page and opens it. Adding HTML to the Web Forms Page In this part of the walkthrough, you will add some static text to the page. To add text to the page 1. At the bottom of the document window, click the Design tab to switch to Design view. Design view displays the page that you are working on in a WYSIWYG-like way. At this point, you do not have any text or controls on the page, so the page is blank except for a dashed line that outlines a rectangle. This rectangle represents a div element on the page. 2. Click inside the rectangle that is outlined by a dashed line. 3. Type Welcome to Visual Web Developer and press ENTER twice. The following illustration shows the text you typed in Design view. 4. Switch to Source view. You can see the HTML that you created by typing in Design view, as shown in the following illustration.
  • 7. Running the Page Before you proceed with adding controls to the page, you can try running it. To run a page, you need a Web server. In a production Web site, you use IIS as your Web server. However, to test a page, you can use the Visual Studio Development Server, which runs locally and does not require IIS. For file system Web site projects, the default Web server in Visual Studio and Microsoft Visual Web Developer Express is the Visual Studio Development Server. To run the page 1. In Solution Explorer, right-click FirstWebPage.aspx and select Set as Start Page. 2. Press CTRL+F5 to run the page. Visual Studio starts the Visual Studio Development Server. An icon appears in the Windows taskbar to indicate that the Visual Studio Development Server is running, as shown in the following illustration. The page is displayed in the browser. Although the page you created has a file-name extension of .aspx, it currently runs like any HTML page. To display a page in the browser you can also right-click the page in Solution Explorer and select View in Browser. 3. Close the browser.
  • 8. Adding and Programming Controls You will now add server controls to the page. Server controls, which include buttons, labels, text boxes, and other familiar controls, provide typical form-processing capabilities for your ASP.NET Web Forms pages. However, you can program the controls with code that runs on the server, not the client. You will add a Button control, a TextBox control, and a Label control to the page and write code to handle the Clickevent for the Button control. To add controls to the page 1. Click the Design tab to switch to Design view. 2. Put the insertion point at the end of the Welcome to Visual Web Developer text and press ENTER five or more times to make some room in the div element box. 3. In the Toolbox, expand the Standard group. 4. Drag a TextBox control onto the page and drop it in the middle of the div element box that has Welcome to Visual Web Developer in the first line. 5. Drag a Button control onto the page and drop it to the right of the TextBox control. 6. Drag a Label control onto the page and drop it on a separate line below the Button control. 7. Put the insertion point above the TextBox control, and then type Enter your name:. This static HTML text is the caption for the TextBox control. You can mix static HTML and server controls on the same page. The following illustration shows how the three controls appear in Design view. Setting Control Properties Visual Studio offers you various ways to set the properties of controls on the page. In this part of the walkthrough, you will set properties in both Design view and Source view. To set control properties 1. Select the Button control, and then in the Properties window, set Text to Display Name. The text you entered appears on the button in the designer, as shown in the following illustration.
  • 9. Note If the Properties window is not displayed, press F4 to display it. 2. 3. Switch to Source view. Source view displays the HTML for the page, including the elements that Visual Studio has created for the server controls. Controls are declared using HTML-like syntax, except that the tags use the prefix asp: and include the attribute runat="server". Control properties are declared as attributes. For example, when you set the Text property for the Buttoncontrol, in step 1, you were actually setting the Text attribute in the control's markup. Note that all the controls are inside a form element, which also has the attribute runat="server". Therunat="server" attribute and the asp: prefix for control tags mark the controls so that they are processed by ASP.NET on the server when the page runs. Code outside of <form runat="server"> and <script runat="server"> elements is sent unchanged to the browser, which is why the ASP.NET code must be inside an element whose opening tag contains the runat="server" attribute. 4. Put the insertion point after asp:Label in the <asp:Label> tag, and then press SPACEBAR. A drop-down list appears that displays the list of properties you can set for a Label control. This feature, referred to as IntelliSense, helps you in Source view with the syntax of server controls, HTML elements, and other items on the page. The following illustration shows the IntelliSense drop-down list for the Labelcontrol.
  • 10. 5. Select ForeColor and then type an equal sign and a quotation mark (="). IntelliSense displays a list of colors. Note You can display an IntelliSense drop-down list at any time by pressing CTRL+J. 6. Select a color for the Label control's text. Make sure you select a color that is dark enough to read against a white background. The ForeColor attribute is completed with the color that you have selected, including the closing quotation mark. Programming the Button Control For this walkthrough, you will write code that reads the name that the user enters into the text box and then displays the name in the Label control. To add a default button event handler 1. Switch to Design view. 2. Double-click the Button control. Visual Studio switches to Source view and creates a skeleton event handler for the Button control's default event, the Click event.
  • 11. Note Double-clicking a control in Designview is just one of several ways you can create event handlers. 3. Inside the handler, type Label1 followed by a period (.). When you type the period after Label, Visual Studio displays a list of available members for the Labelcontrol, as shown in the following illustration. 4. Finish the Click event handler for the button so that it reads as shown in the following code example. C# VB protected void Button1_Click(object sender, System.EventArgs e) { Label1.Text = TextBox1.Text + ", welcome to Visual Studio!"; }
  • 12. 5. Scroll down to the <asp:Button> element. Note that the <asp:Button> element now has the attributeonclick="Button1_Click". This attribute binds the button's Click event to the handler method you coded in the previous step. Event handler methods can have any name; the name you see is the default name created by Visual Studio. The important point is that the name used for the onclick attribute must match the name of a method in the page. Running the Page You can now test the server controls on the page. To run the page 1. Press CTRL+F5 to run the page in the browser. The page again runs using the Visual Studio Development Server. 2. Enter a name into the text box and click the button. The name you entered is displayed in the Label control. Note that when you click the button, the page is posted to the Web server. ASP.NET then recreates the page, runs your code (in this case, the Buttoncontrol's Click event handler runs), and then sends the new page to the browser. If you watch the status bar in the browser, you can see that the page is making a round trip to the Web server each time you click the button. 3. In the browser, view the source of the page you are running. In the page source code, you see only ordinary HTML; you do not see the <asp:> elements that you were working with in Source view. When the page runs, ASP.NET processes the server controls and renders HTML elements to the page that perform the functions that represent the control. For example, the <asp:Button>control is rendered as the HTML <input type="submit"> element. 4. Close the browser. Working with Additional Controls In this part of the walkthrough, you will work with the Calendar control, which displays dates a month at a time. TheCalendar control is a more complex control than the button, text box, and label you have been working with and illustrates some further capabilities of server controls. In this section, you will add a System.Web.UI.WebControls.Calendar control to the page and format it. To add a Calendar control 1. In Visual Studio, switch to Design view. 2. From the Standard section of the Toolbox, drag a Calendar control onto the page and drop it below the divelement that contains the other controls: The calendar's smart tag panel is displayed. The panel displays commands that make it easy for you to perform the most common tasks for the selected control. The following illustration shows the Calendar control as rendered in Design view.
  • 13. 3. In the smart tag panel, choose Auto Format. The Auto Format dialog box is displayed, which allows you to select a formatting scheme for the calendar. The following illustration shows the Auto Format dialog box for the Calendar control.
  • 14. 4. From the Select a scheme list, select Simple and then click OK. 5. Switch to Source view. You can see the <asp:Calendar> element. This element is much longer than the elements for the simple controls you created earlier. It also includes subelements, such as <WeekEndDayStyle>, which represent various formatting settings. The following illustration shows the Calendar control in Source view. (The exact markup that you see in Source view might differ slightly from the illustration.)
  • 15. Programming the Calendar Control In this section, you will program the Calendar control to display the currently selected date. To program the Calendar control 1. In Design view, double-click the Calendar control. A new event handler is created in Source view. 2. Finish the SelectionChanged event handler with the following highlighted code. C# VB protected void Calendar1_SelectionChanged(object sender, System.EventArgs e) { Label1.Text = Calendar1.SelectedDate.ToLongDateString(); } Running the Page You can now test the calendar. To run the page 1. Press CTRL+F5 to run the page in the browser. 2. Click a date in the calendar. The date you clicked is displayed in the Label control.
  • 16. 3. In the browser, view the source code for the page. Note that the Calendar control has been rendered to the page as a table, with each day as a td element containing an a element. 4. Close the browser. Visual Studio Templates for Web Projects .NET Framework 4.5 Visual Studio includes project templates to help you get started when you create a web project. You can create web application projects or web site projects. By considering the most appropriate project type before you begin, you can save time when you create, test, and deploy the web project. Web Project Templates From the File menu, you can select either New Project or New Web Site. The New Project dialog box provides a list of web application templates. Use the web application project template to create web applications that are compiled into an assembly and that provide rich options for deployment. The New Web Site dialog box provides a list of web site templates. Use the Web Site project template when you want to compile the source code dynamically. For more information about the differences between web project types, see Web Application Projects versus Web Site Projects. Note You can install additional products by using the NuGet package manager. In some cases, these products include additional templates for new projects. The lists in this topic show you only the templates that are included by default with Visual Studio 2012. Web Application Templates Web application templates help you create a web project that is compiled into an assembly for deployment. The following table lists templates that appear in the New Project dialog box under the Web category after you select a language (Visual Basic or Visual C#). Project Template More Information ASP.NET Web Forms Application Use this project template to create a web application that is based on ASP.NET Web Forms pages and that includes the following functionality. You can choose not to use any of these features when they are not required for your application.  A master page.  A cascading style sheet.  Login security that uses the ASP.NET membership system.
  • 17.  Ajax scripting that uses jQuery.  Navigation that uses a menu control. By default, the ASP.NET Web Application project template includes the following:  Folders to contain membership pages, client script files, and cascading style sheet files.  A data folder (App_Data), which is granted permissions that allow ASP.NET to read and write to it at run time.  A master page (the Site.master file).  Web pages named Default.aspx, Contact.aspx, and About.aspx. These content pages are based on the default master.  A global application class (Global.asax file).  A Web.config file.  A Packages.config file.  For more information, see ASP.NET Web Application Projects and Web Application Projects versus Web Site Projects in Visual Studio. ASP.NET MVC 3 Web Application Use this project template to create web applications that use a model-view- controller pattern, using the ASP.NET MVC 3 release. The MVC pattern helps separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. In addition, this project template promotes test-driven development (TDD). For more information, see ASP.NET MVC Overview. ASP.NET MVC 4 Web Application Use this project template to create web applications that use a model-view- controller pattern, using the ASP.NET MVC 4 release. For more information, see ASP.NET MVC Overview. ASP.NET Empty Web Application This template creates an ASP.NET web application that includes a Web.config file, but no other files. Use this project template when you do not require the functionality built into the standard template. ASP.NET Dynamic Data Entities Web Application Use this project template to create a Dynamic Data web application that uses the ADO.NET Entity Framework. This type of Dynamic Data web application can target any relational database. Dynamic Data automatically generates a functional web application for viewing and editing data, based on the schema of the data. For more information, see ASP.NET Dynamic Data Overview. ASP.NET AJAX Server Control Use this project template to create a web server control for ASP.NET Web Forms pages that incorporates Ajax functionality. The control consists of
  • 18. server and client code that work together to produce rich client behavior. For more information, see ASP.NET AJAX Overview. ASP.NET AJAX Server Control Extender Use this project template to create an Ajax component that enhances the client capabilities of standard ASP.NET web server controls. For more information, see ASP.NET AJAX Extender Controls Overview. ASP.NET Server Control Use this project template to create a custom ASP.NET web server control that can be used in ASP.NET Web Forms pages. For more information, see Developing Custom ASP.NET Server Controls. Web Site Templates Web site templates help you create a web project that by default is compiled dynamically. The following table lists templates that appear in the New Web Site dialog box. Project Template More Information ASP.NET Web Forms Site Use this project template to create a website that includes the following functionality. You can choose not to use any of these features when they are not required for your application.  A master page.  A cascading style sheet.  Login security that uses the ASP.NET membership system.  Ajax scripting that uses jQuery.  Navigation using a menu control. By default, the ASP.NET Web Site project template includes the following:  Folders to contain membership pages, client script files, and cascading style sheet files.  A data folder (App_Data), which is granted permissions that allow ASP.NET to read and write to it at run time.  A master page (.master file).  Web pages named Default.aspx and About.aspx. In the project template, these pages are content pages that use default master page.  A global application class (Global.asax file).  A Web.config file. For more information, see Walkthrough: Creating a Basic Web Page in Visual Studio. ASP.NET Web Site (Razor v2) Use this project template to create a website that uses ASP.NET Web Pages version 2 with Razor syntax. For more information, see Introduction to ASP.NET Web Programming Using the Razor Syntax. ASP.NET Web Site (Razor) Use this project template to create a website that uses ASP.NET Web Pages with the Razor syntax. For more information, see Introduction to ASP.NET
  • 19. Web Programming Using the Razor Syntax. ASP.NET Empty Web Site This template creates an ASP.NET website that includes a Web.config file but no other files. Use this project template when you do not require the functionality built into the standard. ASP.NET Dynamic Data Entities Web Site Use this project template to create a Dynamic Data website that uses the ADO.NET Entity Framework. This type of Dynamic Data web application can target any relational database. Dynamic Data automatically generates a functional web application for viewing and editing data, based on the schema of the data. For more information, see ASP.NET Dynamic Data. WCF Service Use this project template to create a Windows Communication Foundation (WCF) service. You can extend the service so that a website, web application, Silverlight application, Ajax application, or other client can call it. For more information, see Windows Communication Foundation. ASP.NET Reports Web Site Use this project template to create an ASP.NET website that contains a report (.rdlc file), a default ASP.NET Web Forms page (.aspx file) that contains a ReportViewer control, and a Web.config file. For more information, see Microsoft Reports. Walkthrough: Creating a Basic Web Forms Page with Code Separation in Visual Studio Other Versions When you create ASP.NET Web Forms pages and write code in them, you can select from two models for how to manage the visible elements (controls and text) and your programming code. In the single-file model, the visible elements and code are kept together in the same file. In the alternative model, called
  • 20. "code separation," the visible elements are in one file and the code is in another file, referred to as the "code-behind" file. This walkthrough introduces you to Web Forms pages that use code separation. Note This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages. The single-file model is introduced in Walkthrough: Creating a Basic Web Forms Page in Visual Studio. The walkthrough you are reading now shows you how to create a Web page with the same functionality as the page in the single-file walkthrough, but with a focus on using code separation. The choice between using single-file pages and pages with code separation is primarily one of convenience and personal preference. Working with both models in Microsoft Visual Studio is similar; both models have approximately equal support in the editor. Both models have equivalent performance when the page runs. The page with code separation makes it more practical to let a Web designer work on the layout of a page while a programmer creates the code for the page, because the two pages can be edited separately. Tasks illustrated in this walkthrough include:  Creating an ASP.NET Web Forms page with code separation.  Adding server controls.  Adding event handlers.  Running pages with the Visual Studio Development Server. Prerequisites In order to complete this walkthrough, you will need:  Visual Studio or Visual Web Developer Express. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings. Creating a Web Site Project and Page In this part of the walkthrough, you will create a Web site project and add a new page to it. You will also add HTML text and run the page in your Web browser. If you have already created a Web Forms Web site project in Visual Studio (for example, by following the steps inWalkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and skip to "Creating a New Page" later in this walkthrough. Otherwise, create a new Web site project and page by following these steps. To create a file system Web site project 1. Open Visual Studio or Visual Web Developer Express. 2. In the File menu, click New Web Site.
  • 21. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). Creating a New Web Forms Page When you create a new Web site project, Visual Studio adds a Web Forms page named Default.aspx. By default, Visual Studio creates a page with code separation. To add a page with code separation to the Web site 1. Close the Default.aspx page. To do this, right-click the tab with the file name in it and then click Close. 2. In Solution Explorer, right-click the Web site (for example, C:BasicWebSite) and then click Add New Item. 3. Under Installed Templates, click Visual Basic or Visual C# and then select Web Form from the list. 4. In the Name box, enter WebPageSeparated. 5. Make sure that the Place code in separate file check box is selected. 6. Make sure that the Select master page check box is cleared. For this walkthrough, you will create a page that does not use the master page that is included in the Web site project. 7. Click Add. Visual Studio creates two files. The first file, WebPageSeparated.aspx, will contain the page's text and controls, and is opened in the editor. A second file, WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs (depending on what programming language you selected), is the code file. You can see both files in Solution Explorer by clicking the plus sign (+) next to the WebPageSeparated.aspx file; the code file has been created but is not open. You will open it later in the walkthrough when you write code. Adding HTML to the Web Forms Page In this part of the walkthrough, you will add some static HTML text to the WebPageSeparated.aspx page. To add text to the page 1. Click the Design tab at the bottom of the document window to switch to Design view. Design view displays the page you are working on in a WYSIWYG-like way. At this point, you do not have any text or controls on the page, so the page is blank. 2. Place the insertion pointer in the div element that is already on the page. 3. Type the words Welcome to Visual Studio Using Code Separation. 4. Switch to Source view. You can see the HTML that you created by typing in Design view. At this stage, the page looks like an ordinary HTML page. The only difference is in the <%@ Page %> directive at the top of the page. Adding and Programming Server Controls In this part of the walkthrough, you will add server controls to the Web Forms page: a button, text box, and label control. You will also write code to handle the button's Click event. Server controls, which
  • 22. include buttons, labels, text boxes, and other familiar controls, provide typical form-processing capabilities for your ASP.NET Web Forms pages. However, you can program the controls with code that runs on the server, not the client. To add controls to the page 1. Click the Design tab to switch to Design view. 2. Place the insertion pointer after the text that you added previously. 3. Press ENTER a few times to make some room. 4. From the Standard tab in the Toolbox, drag three controls onto the page: a TextBox control, a Button control, and a Label control. 5. Put the insertion pointer in front of the text box and type Enter your name:. This static HTML text is the caption for the TextBox control. You can mix static HTML and server controls on the same page. Setting Server Control Properties Visual Studio offers you various ways to set the properties of server controls on the page. In this part of the walkthrough, you will work with properties in both Design view and Source view. To set control properties 1. Select the Button control and in the Properties window set its Text property to Display Name. 2. Switch to Source view. Source view displays the HTML markup for the page, including the elements that Visual Studio has created for the server controls. Server controls are declared using HTML-like syntax, except that the tags use the prefix asp: and include the attribute runat="server". Server control properties are declared as attributes. For example, when you set the button's Text property in Step 1, you were actually setting the Text attribute in the control's markup. Note that all the controls are inside a form element that also has the attribute runat="server". Therunat="server" attribute and the asp: prefix for control tags mark the controls so that they are processed by ASP.NET when the page runs. Programming the Button Control For this walkthrough, you will write code that reads the name that the user enters in the text box and then displays it in the Label control. To add a default button event handler 1. Switch to Design view 2. Double-click the Button control. Visual Studio opens the WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs file in a separate window in the editor. The file contains a skeleton Click event handler for the button. 3. Complete the Click event handler by adding the following highlighted code. C# VB protected void Button1_Click(object sender, System.EventArgs e) { Label1.Text = TextBox1.Text + ", welcome to Visual Studio!"; }
  • 23. Notice that as you type, IntelliSense helps you with context-sensitive choices. This is identical to the behavior when you are coding in a single-file page. Examining the Page and Code File You now have two files that make up the complete Web Forms page named WebPageSeparated: WebPageSeparated.aspx and WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs. In this section of the walkthrough, you will examine how these files are structured and how they relate to each other. To examine the page and code file 1. Click the WebPageSeparated.aspx tab at the top of the editor window to switch to the page file. 2. Switch to Source view. At the top of the page is an @ Page directive that binds this page to the code file. The directive looks like the following code. C# VB <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebPageSeparated.aspx.cs" Inherits="WebPageSeparated" %> (The line does not wrap in the editor, and the language attribute and file name extensions will match the programming language you selected.) When the page runs, ASP.NET dynamically creates an instance of a class representing the Web Forms page. The Inherits attribute identifies the class defined in the code-behind file from which the .aspx page is derived. By default, Visual Studio uses the page name as the basis for the class name in the code-behind file. The CodeFile attribute identifies the code file for this page. In simple terms, the code-behind file contains the event-handling code for your page. 3. Click the WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs tab to switch to the code file. The code file contains code that is similar to a class definition. However, it is not a complete class definition; instead, it is a partial class that contains only a portion of the complete class that will make up the page. Specifically, the partial class defined in the code file contains the event handlers and other custom code that you write. At run time, ASP.NET generates another partial class containing your user code. This complete class is then used as the base class that is used to render the page. For more information, see ASP.NET Page Class Overview. Running the Page You can now test the page. To run the page 1. Press CTRL+F5 to run the page in the browser. The page runs using the Visual Studio Development Server. 2. Enter a name in the text box and click the button. The name you entered is displayed in the Label control. 3. In the browser, view the source of the page you are running. 4. Close the browser.
  • 24. The page works exactly the same as it would if it were a single-file page. (If you followed the steps inWalkthrough: Creating a Basic Web Forms Page in Visual Studio to create a single-file page, you can compare the two pages to see that they are the same when running.) Next Steps This walkthrough has illustrated how to create and edit a Web Forms page that uses code separation. From the perspective of creating and running the page, there is not a significant difference between a single-file page and a page with code separation. You might want to explore other features. For example, you might want to:  Create different types of Web sites. In addition to creating a file-system Web site as you did in this walkthrough, you can work with Web site projects using Microsoft Internet Information Services (IIS), and FTP, and you can work with Web application projects. For details, see Types of Web Site Projects in Visual Studioand Web Application Projects versus Web Site Projects in Visual Studio.  Add data access to Web Forms pages. For details, see Walkthrough: Basic Data Access Using the SqlDataSource Control in Web Pages.  Learn about the debugger for Web pages. For details, see Walkthrough: Debugging Web Pages in Visual Web Developer.  Create a consistent site layout using master pages. For details, see Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer. Walkthrough: Basic HTML Editing in Visual Studio for Web Forms Pages .NET Framework 4.5 Other Versions Microsoft Visual Studio 2012 provides a rich HTML editing experience for Web Forms pages. The Visual Studio HTML editor lets you work in WYSIWYG mode and also lets you work directly with HTML markup for finer control. This walkthrough introduces you to the HTML editing features of Visual Studio. Note This topic applies to ASP.NET Web Forms pages. You can use Source view for editing pages
  • 25. in ASP.NET MVC (Model View Controller)or ASP.NET Web Pages applications (.cshtml files), but Design view is fully supported only for Web Forms pages. Web server controls are used only in Web Forms pages. Tasks illustrated in this walkthrough include the following:  Creating and editing HTML in Design view.  Creating and editing HTML in Source view.  Using Split view.  Using navigation tools to move quickly through your HTML tags. Prerequisites In order to complete this walkthrough, you need the following:  Visual Studio or Visual Studio Express for Web installed on your computer. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  A general understanding of how to work in Visual Studio. For an introduction to how to create Web Forms pages in Visual Studio, see Walkthrough: Creating a Basic Web Forms Page in Visual Studio. Creating the Web Site and Web Forms Page If you have already created a Web Forms site in Visual Studio or Visual Studio Express for Web (for example, by completing Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that web site and go to the next section. Otherwise, create a website and Web Forms page by following these steps. Note This walkthrough uses a web site project. You could use a web application project instead. For information about the difference between these web project types, see Web Application Projects versus Web Site Projects. To create a file system website 1. Open Visual Studio or Visual Studio Express for Web. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed, click Visual Basic or Visual C# and then select ASP.NET Empty Web Site. For this walkthrough, you create a website that does not include prebuilt pages and other resources.
  • 26. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your website. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a website project that includes a Web.config file. 6. In Solution Explorer, right-click the root of your Web site, and then click Add New Item. 7. Select Web Form, name the file Default.aspx, and then click Add. Working in Design View In this part of the walkthrough, you will learn how to work in Design view, which provides a WYSIWYG- like view of the Web Forms page. You can add text by typing, as you would in a word-processing program. You can format text directly with formatting commands or by creating in-line styles. Design view displays your page in a way that is similar to how it will appear in a browser, with some differences. The first difference is that in Design view, the text and elements are editable. The second difference is that to help you edit your pages, Design view displays some elements and controls that will not appear in the browser. Additionally, some elements, such as HTML tables, have a special Design view rendering that adds additional space for the editor. Overall, Design view helps you visualize your page, but it is not an exact representation of how the page will render in a browser. To add and format static HTML in Design view 1. If you are not in Design view, click Design, which is located at the lower left of the window. 2. At the top of the page, type ASP.NET Web Page. 3. Highlight the text to select it, and then on the Formatting toolbar click Heading 1. 4. Press ENTER after ASP.NET Web Page, and then type This page is powered by ASP.NET. 5. Highlight the text, then, on the Format menu, click New Style.
  • 27. The New Style dialog box appears. 6. Select the Apply new style to document selection option. 7. Select a font from the font-family drop-down list and then click Apply. The font family is applied to the selected text.
  • 28. 8. Under Category, click Block, and then select (value) from the line-height drop-down list. Enter a value for line height.
  • 29. 9. Select (value) from the letter-spacing dropdown list. Enter a value for letter spacing. Click Apply to see the values applied to the selected text. 10. Click OK. Viewing Tag Information When you are working in Design view, you might want to see tags such as div and span that do not have a visual rendering. To see HTML design surface tags in Design view  On the View menu, point to Visual Aids, and make sure that ASP.NET Non-visual Controls is selected. The designer displays symbols for paragraphs, line breaks, and other tags that do not render text. The symbols are not all shown at the same time, but when you click a visual element, the nonvisual element that precedes it is shown. Adding Controls and Elements In Design view, you can drag controls from the toolbox onto the page. You can add some elements, such as HTML tables, using a dialog box. In this section, you add some controls and a table so that you have elements to work with later in the walkthrough. To add controls and a table 1. Put the cursor to the right of the text This page is powered by ASP.NET, and then press ENTER. 2. From the Standard group in the Toolbox, drag a TextBox control onto the page and drop it in the space you created in the preceding step.
  • 30. Note You can also add a control by double-clicking it. 3. 4. Drag a Button control onto the page and drop it to the right of the TextBox control that you added in the preceding step. The TextBox and Button controls are ASP.NET web server controls, not HTML elements.
  • 31. 5. Put the cursor to the right of the Button control and then press ENTER. 6. On the Table menu, click Insert Table. The Insert Table dialog box appears.
  • 32. 7. Click OK. The Insert Table dialog box provides options for configuring the table that you are creating. However, for this walkthrough, you can use a default table layout.
  • 33. Creating Hyperlinks Design view provides builders and other tools to help you create HTML elements that require property settings. To create a hyperlink 1. In the text This page is powered by ASP.NET, highlight ASP.NET to select it. 2. On the Format menu, click Convert to Hyperlink.
  • 34. The Hyperlink dialog box appears. 3. In the URL box, type http://www.asp.net. 4. Click OK. Setting Properties in the Properties Window You can change the look and behavior of the elements on the page by setting values in the Properties window. To set properties by using the Properties window 1. Select the Button control that you added in "Adding Controls and Elements" earlier in this walkthrough. 2. In Properties window, set Text to Click Here, and ForeColor to a different color.
  • 35. 3. Place the cursor in the ASP.NET hyperlink that you created in the preceding section. Notice that in the Properties window, the hreef property for the a element is set to the URL that you provided for the hyperlink. Testing the Page You can see the results of your editing by viewing the page in the browser. To start the page in the browser externally  Right-click the page, and then click View in Browser. If you are prompted to save your changes, click Yes. Visual Studio starts IIS Express, which is a local web server that you can use to test pages without using a full IIS server. Note You can run pages in several ways. If you press CTRL+F5, Visual Studio performs the start action that is configured on the property page for Start Options. The default start option for CTRL+F5 is to run the current page; that is, the page that is currently active in Source or Designview. You can also run pages in the debugger. For more information, see Walkthrough: Debugging Web Pages in Visual Web Developer. Changing the Default View By default, Visual Studio opens new pages in Source view. To change the default page view to Design view 1. On the Tools menu, click Options 2. Make sure that the Show all settings options is selected at the bottom of the dialog box. 3. Open the HTML Designer node and then select General. Under Start Pages in, click Design view.
  • 36. Working in Source View Source view lets you edit the markup of the page directly. The Source view editor gives you many features that help you as you create HTML and ASP.NET controls. You can use the toolbox in Source view just as you do in Design view to add new elements to the page. To add elements in Source view 1. Switch to Source view by clicking Source, which is located at the bottom of the window. The controls that you have added are created as <asp:> elements. For example, the Button control is the<asp:button> element. The property settings that you made are preserved as attribute settings in the opening <asp:button> tag. 2. From the HTML group in the Toolbox (not the Standard group), drag a Table element onto the page and place it just above the </form> tag. The editor also helps you when you type markup manually. For example, the editor provides context- sensitive choices that finish HTML tags and attributes as you type. The editor also provides error and warning information on markup by underlining questionable markup with a wavy line. You can see the error or warning information by holding the mouse over the markup text. To edit HTML in Source view 1. Position the cursor above the closing </form> tag, and then type a left angle bracket (<). Notice that the editor offers you a list of tags that are appropriate in the current context.
  • 37. 2. Enter "a" to create an anchor tag, and then press the SPACEBAR. The editor displays a list of attributes that are appropriate for an anchor tag. Note The letter a (anchor element) might not appear as an option, depending on the validation target that is set for the site or the page. However, you can still create an anchor element by entering "a" without selecting an item in the drop-down list. Validation targets are discussed later in this topic.
  • 38. 3. In the list, click href, and then type an equal sign (=) and a double quotation mark ("). The editor offers you a list of currently available pages to link to.
  • 39. 4. In the file list, double-click Default.aspx, press the spacebar, and then type a right angle bracket (>) to close the tag. The editor inserts a closing </a> tag. 5. Finish the anchor element by entering the text Home between the opening and closing tags. The element now resembles the following example: <a href="Default.aspx">Home</a> 6. Position the cursor just above the closing </form> tag, and then type <invalid>. The editor underlines the tag with a wavy line, indicating that the tag is not a recognized HTML tag. 7. Remove the tag that you created in the preceding step. Examining HTML Formatting An important feature of the page designer is that it preserves the HTML formatting that you apply to the page. However, you can explicitly specify that the editor reformat the document. To examine HTML formatting 1. Reformat the attributes for the Button control by aligning the attributes so that the declarative syntax looks like the following: 2. <asp:Button 3. id="Button1" 4. runat="server" 5. Font-Bold="True" 6. ForeColor="Blue" 7. Text="Click Here" />
  • 40. Notice that after you indent the first attribute, when you press ENTER in the tag, subsequent lines are indented to match. 8. Switch to Design view. 9. Right-click the Button control, and then click Copy. 10. Position the cursor below the Button control, right-click, and then click Paste. Visual Studio creates a button with the ID property set to Button2. 11. From the Standard group in the Toolbox, drag a third Button control onto the page, which creates a button named Button3. 12. Switch to Source view. Notice that Button2 is formatted exactly the way that you formatted Button1. On the other hand, Button3is formatted using the default formatting for Button controls. Note For more information on how to customize the formatting of individual elements, see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages. 13. Edit the document so that Button1 and Button2 are on the same line without a space between them, as shown in the following example: 14. <asp:Button ID="Button1" runat="server" Font-Bold="True" 15. ForeColor="Blue" Text="Click Here" /><asp:Button ID="Button2" 16. runat="server" Font-Bold="True" ForeColor="Blue" Text="Click Here"/> The elements can wrap, but the beginning of Button2 must immediately follow the end of Button1 (the />character). 17. Switch to Design view. Notice that Button1 and Button2 are right next to each other without a space between them. 18. Switch to Source view 19. On the Edit menu, in the Advanced submenu, click Format Document. The document is reformatted, but Button1 and Button2 remain on the same line. If the editor separated the buttons, it would introduce a space during rendering. Therefore, the editor does not change the formatting that you have created. Working in Split View You can see both the Design view and Source view windows at the same time by using Split view. To view a page in Split view  Switch to Split view by clicking Split, which is located at the lower left of the window. Notice that theSource view window occupies the upper half of the screen, and the Design view window the lower half. Notice also that the two views are synchronized. If you double-click an item in one view to select it, the corresponding item in the other view is highlighted. Navigating Between Elements As pages become larger and more complex, it is useful to be able to find tags quickly and to reduce the clutter in the page. Visual Studio provides the following tools to help you with these tasks when you are working in Source view:  Document Outline, which provides a complete view of the document.
  • 41.  The tag navigator, which provides information about the currently selected tag and where it is in the page hierarchy. To start, add more elements to the page so that you can examine the navigation features. To add elements 1. Switch to Design view. 2. From the HTML group in the Toolbox, drag a Table control into a cell of the table that you created in "Working in Source View," earlier in this walkthrough. 3. From the Standard group in the Toolbox, drag a Button control into the middle cell of the nested table. With several nested elements on the page, you can see how Document Outline provides quick navigation to any tag in the page. To navigate using Document Outline 1. Switch to Source view. 2. On the View menu, click Document Outline. 3. In Document Outline, click Button4. In the editor, the <Button4> control that you added in the preceding procedure is selected. The tag navigator provides information about the currently selected tag and where it is in the page hierarchy. To navigate using tag navigator 1. Position the cursor in the Button element.
  • 42. Notice the tag navigator at the bottom of the window, which shows the <asp:button> tag and its parent tags. The tag navigator includes the ID of the element, if any, so that you can identify which element is being displayed. The tag navigator also displays the assigned cascading style sheet, if any, that was set with the Classattribute. 2. In the tag navigator, click the <table> tag that is closest to the <asp:button#Button4> tag. The tag navigator moves to the inner <table> element and selects it.
  • 43. 3. In the tag navigator, click the <td> tag to the left of the selected <table> tag. The whole cell that contains the nested table is selected. Note You can click to select either the tag or its contents by using the drop-down list in the tag navigator tag. By default, clicking a tag in the tag navigator selects the tag and its contents. You can also use the tag navigator to help you move or copy elements. To move or copy elements by using the tag navigator 1. Using the tag navigator, select the <tr> tag that contains the Button4 control. 2. Press CTRL+C to copy the tag. 3. Use the tag navigator to move to the outer table. 4. In Source view, place the cursor between the <table> tag and the first <tr> tag. 5. Press CTRL+V to paste the copied row into the table. 6. Switch to Design view. Notice that the new row has been added, including a Button control.
  • 44. Formatting Text  The Formatting toolbar applies inline styles for most settings. Bold and italic formatting is applied by using the b and i tags. Paragraph formatting is applied a block tag, such as p (for normal), pre (for formatted), and so on. Paragraph alignment is applied by using inline styles to conform with XHTML 1.1 standards.  The designer also lets you create a style block and a link to a cascading style sheet. For more information, seeWalkthrough: Creating and Modifying a CSS File.  By default, the editor creates markup that is compatible with the XHTML5 standard. The editor converts all HTML tag names to lowercase, even if you type them in uppercase. The editor also encloses attribute (property) values in double quotation marks. For more information, see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages. To change the default markup validation 1. In Source view, right-click the page, and then click Formatting and Validation. 2. In the Options dialog box, expand Text Editor, expand HTML, and then click Validation. 3. In the Target list, enter a validation type. Next Steps This walkthrough has given you an overview of the HTML capabilities of the web page editor. This includes how to create HTML in Design view and Source view, basic formatting, and navigation. To learn more about the editing facilities in Visual Studio, consult the following resources.  To learn about the additional capabilities of the HTML editor, including custom formatting options, outlining, and HTML validation, see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages.  To learn how to work with styles in cascading style sheets, see Walkthrough: Creating and Modifying a CSS File. Walkthrough: Basic Data Access Using the SqlDataSource Control in Web Pages Other Versions This walkthrough shows you how to create a simple data-bound page by using controls that are specially designed for data access. During this walkthrough, you will learn how to do the following:  Connect to a Microsoft SQL Server database in the Microsoft Visual Web Developer Web development tool.
  • 45.  Use drag-and-drop editing to create data-access elements that can be used in the page without code.  Use the SqlDataSource control to manage data access and binding.  Display data with the GridView control.  Configure the GridView control to allow for sorting and paging.  Create a filtered query that displays only selected records. A Visual Studio project with source code is available to accompany this topic: Download. Prerequisites In order to complete this walkthrough, you will need the following:  Visual Studio or Visual Web Developer Express installed on your computer. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  Access to the SQL Server Northwind database. The simplest option is to use the file-based copy of Northwind that is included in the code example download for this topic. As an alternative, you can download and install a version of Northwind to run on an instance of SQL Server on your computer or your local network. For information about downloading and installing the SQL Server sample Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site. Note If you need information about how to log on to the computer running SQL Server, contact the server administrator. Creating the Web Site If you have already created a Web site in Visual Studio or Visual Web Developer Express (for example, by completingWalkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and go to the next section. Otherwise, create a new Web site and page by following these steps. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Studio or Visual Web Developer Express. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
  • 46. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). Adding a GridView Control to Display Data To display data on an ASP.NET Web page, you need the following:  A connection to a data source (such as a database). In the following procedure, you will create a connection to the SQL Server Northwind database.  A data source control on the page, which executes queries and manages the results of the queries.  A control on the page to actually display the data. In the following procedure, you will display data in a GridView control. The GridView control will get its data from the SqlDataSource control. You can add these elements to the Web site separately. However, it is easiest to start by visualizing the data display using GridView control, and then using wizards to create the connection and data source control. The following procedure explains how to create all three of the elements that you must have to display data on the page. To add and configure a GridView control for displaying data 1. In Visual Web Developer, switch to Design view. 2. From the Data folder in the Toolbox, drag a GridView control onto the Default.aspx page. 3. If the GridView Tasks shortcut menu does not appear, right-click the GridView control, and then click Show Smart Tag. 4. On the GridView Tasks menu, in the Choose Data Source list, click <New data source>. The Data Source Configuration dialog box appears.
  • 47. 5. Click Database. This specifies that you want to obtain data from a database that supports SQL statements. This includes SQL Server and other OLE-DB–compatible databases. In the Specify an ID for the data source box, a default data source control name appears (SqlDataSource1). You can leave this name. 6. Click OK. The Configure Data Source wizard appears, displaying a page on which you can choose a connection.
  • 48. 7. Click New Connection. 8. In the Choose Data Source dialog box, under Data source, click Microsoft SQL Server, and then clickContinue. The Add Connection dialog box appears. 9. In the Server name box, enter the name of the SQL Server that you want to use.
  • 49. 10. For the logon credentials, select the option that is appropriate for accessing the SQL Server database (integrated security or specific ID and password) and if it is required, enter a user name and password. 11. Click Select or enter a database name, and then enter Northwind. 12. Click Test connection, and when you are sure that it works, click OK. The Configure Data Source - <DataSourceName> wizard appears and the connection information is filled in. 13. Click Next. The wizard appears, displaying a page on which you can choose to store the connection string in the configuration file. Storing the connection string in the configuration file has two advantages: o It is more secure than storing the connection string in the page. o You can reuse the same connection string in multiple pages. 14. Make sure that the Yes, save this connection as check box is selected, and then click Next. (You can leave the default connection string name of NorthwindConnectionString.) The wizard appears, displaying a page on which you can specify the data that you want to fetch from the database.
  • 50. 15. Under Specify columns from a table or view, in the Name list, click Customers. 16. Under Columns, select the CustomerID, CompanyName, and City check boxes. The wizard appears, displaying the SQL statement that you are creating in a box at the bottom of the page. Note The wizard lets you specify selection criteria (a WHERE clause) and other SQL query options. For this part of the walkthrough, you will create a simple statement without selection or sort options. 17. Click Next. 18. Click Test Query to make sure that you are fetching the data you want. 19. Click Finish. The wizard closes and you are returned to the page. Running the wizard has accomplished two tasks: o The wizard created and configured a SqlDataSource control (named SqlDataSource1), which incorporates the connection and query information that you specified.
  • 51. o The wizard bound the GridView control to the SqlDataSource. Therefore, the GridView control will display data that is returned by the SqlDataSource control. If you view the properties for the SqlDataSource control, you can see that the wizard has created values for theConnectionString and SelectQuery properties. Note You can easily change the look of the GridView control. In Designview, right-click the GridView control, and then click Show Smart Tag. On the GridView Tasks menu, click Auto Format, and then apply a scheme. Testing the Page You can now run the page. To test the page 1. Press CTRL+F5 to run the page. The page appears in the browser. The GridView control displays all data rows from the Customers table. 2. Close the browser. Adding Sorting and Paging You can add sorting and paging to the GridView control without writing any code. To add sorting and paging 1. In Design view, right-click the GridView control, and then click Show Smart Tag. 2. On the GridView Tasks shortcut menu, select the Enable Sorting check box. The column headings in the GridView control change to links. 3. On the GridView Tasks menu, select the Enable Paging check box. A footer is added to the GridView control with page number links. 4. Optionally, use Properties to change the value of the PageSize property from 10 to a smaller page size. 5. Press CTRL+F5 to run the page. You will be able to click a column heading to sort by the contents of that column. If there are more records in the data source than the page size of the GridView control, you will be able to use the page navigation links at the bottom of the GridView control to move between pages. 6. Close the browser. Adding Filtering Frequently you want to display only selected data in the page. In this part of the walkthrough, you will modify the query for the SqlDataSource control so that users can select customer records for a particular city. First, you will use a TextBox control to create a text box in which users can type the name of a city. Then, you will change the query to include a parameterized filter (WHERE clause). As part of that process, you will create a parameter element for the SqlDataSource control. The parameter element establishes how the SqlDataSource control will get the value for its parameterized query—namely, from the text box. When you are finished with this part of the walkthrough, the page might look similar to the following in Design view.
  • 52. To add the text box for specifying a city 1. From the Standard group in the Toolbox, drag a TextBox control and a Button control onto the page. The Button control is used only to post the page to the server. You will not need to write any code for it. 2. In Properties, for the TextBox control, set ID to textCity. 3. If you want, type City or similar text before the text box to act as a caption. 4. In Properties for the Button control, set Text to Submit. You can now modify the query to include a filter. To modify the query with a parameterized filter 1. Right-click the SqlDataSource control, and then click Show Smart Tag. 2. On the SqlDataSource Tasks menu, click Configure Data Source. The Configure Data Source - <Datasourcename> wizard appears. 3. Click Next. The wizard displays the SQL command that is currently configured for the SqlDataSource control. 4. Click WHERE. The Add WHERE Clause page appears. 5. In the Column list, click City. 6. In the Operator list, click =. 7. In the Source list, click Control. 8. Under Parameter properties, in the Control ID list, click textCity.
  • 53. The previous five steps specify that the query will get the search value for City from the TextBox control that you added in the preceding procedure. 9. Click Add. The WHERE clause that you have created appears in a box at the bottom of the page. 10. Click OK to close the Add WHERE Clause page. 11. In the Configure Data Source - <DataSourceName> wizard, click Next. 12. On the Test Query page, click Test Query. The wizard appears, displaying the Parameter Values Editor page, which prompts you for a value to use in the WHERE clause. 13. In the Value box, type London, and then click OK. The customer records for London appear. 14. Click Finish to close the wizard. You can now test filtering. To test filtering 1. Press CTRL+F5 to run the page. 2. In the text box, type London, and then click Submit. A list of customers from the city of London appears in the GridView control. 3. Try other cities, such as Buenos Aires and Berlin.
  • 54. Walkthrough: Creating Master/Detail Web Pages in Visual Studio Other Versions Many Web pages display data in more than one way, often displaying data from related tables. This walkthrough shows you various ways to work with data in multiple controls and from multiple tables, including those that have a master/detail relationship. Tasks illustrated in this walkthrough include:  Populating a drop-down list with database data.  Creating filters — SQL statements with a WHERE clause (parameterized queries).  Displaying filtered data based on the user's selection in a drop-down list.  Displaying details about a selected record using the DetailsView control.  Selecting a record in one page and displaying a related record in a second page. Prerequisites In order to complete this walkthrough, you will need:  Visual Studio or Visual Web Developer. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site. Note If you need information about how to log on to the computer running SQL Server, contact the server administrator.
  • 55.  Microsoft Data Access Components (MDAC) version 2.7 or later. If you are using Microsoft Windows XP or Windows Server 2003 or a later version of Windows, you already have MDAC 2.7. However, if you are using Microsoft Windows 2000, you might to need to upgrade the MDAC already installed on your computer. For more information, see the article " Microsoft Data Access Components (MDAC) Installation" in the MSDN Library. Creating the Web Site If you have already created a Web site project (for example, by following the steps in Walkthrough: Creating a Basic Web Forms Page in Visual Studio or Walkthrough: Basic Data Access Using the SqlDataSource Control in Web Pages), you can use that Web site and skip to the next section, "Connecting to SQL Server." Otherwise, create a new Web site and page by following these steps. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Studio or Visual Web Developer. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). Connecting to SQL Server To work with data, you need to establish a connection to a database. In this walkthrough, you will create a connection independently of working with Web pages or controls. To create a connection to SQL Server 1. Press CTRL+ALT+S to display the Database Explorer. In Database Explorer, right-click Data Connectionsand choose Add Connection. The Change Data Source dialog box is displayed. 2. In the Change Data Source dialog box, select Microsoft SQL Server. and click OK. 3. In the Add Connection dialog box, do the following: o Enter or select the name of your SQL Server computer. For a server on your computer, enter (local). o Select Use SQL Server Authentication. o Enter a user name and password. o Select Save my password. o Select Northwind as the database. 4. Click Test Connection, and when you are sure that it works, click OK. The connection is added to Server Explorer. Using a Drop-Down List as the Master
  • 56. In this part of the walkthrough, you will add a drop-down list to a page and populate it with a list of categories from the Northwind table. When users select a category, the page will display the products for that category. To create and populate a drop-down list 1. Switch to or open the Default.aspx page. If you are working with a Web site you had already created, add or open a page that you can work with in this walkthrough. 2. Switch to Design view. 3. Type Select Products By Category in the page and format the text as a heading using the Block Formatdrop-down list above the Toolbox. 4. From the Standard group in the Toolbox, drag a DropDownList control onto the page. 5. In the DropDownList Tasks, select the Enable AutoPostBack check box. This configures the control so that it causes the page to post back to the server whenever a selection is made from the list, rather than waiting until the user clicks a button. 6. In the DropDownList Tasks, select Choose Data Source. The Choose Data Source wizard starts. 7. In the Select a data source list, click <New Data Source>. The Data Source Configuration Wizard dialog box is displayed. 8. Select Database. This specifies that you want to get data from a database that supports SQL statements. (This includes SQL Server and other OLE-DB-compatible databases.) In the Specify an ID for the data source box, a default data source control name is displayed (SqlDataSource1). You can leave this name. 9. Click OK. The wizard displays the Configure Data Source - SqlDataSource1 page in which you can select a data connection. 10. From the drop-down list, select the Northwind connection you created earlier in the walkthrough. 11. Click Next. The wizard displays a page in which you can choose to store the connection string in the configuration file. 12. Be sure the Yes, save this connection as check box is selected, and then click Next. (You can leave the default connection string name.) The wizard displays a page in which you can specify what data you want to retrieve from the database. 13. From the Name list under Table or View Options, select Categories. 14. In the Columns box, select CategoryID and CategoryName. 15. Click Next. 16. Click Test Query to be sure that you are getting the data you want. 17. Click Finish. The Data Source Configuration Wizard is displayed, with the name of the data source control you have configured displayed. 18. From the Select a data field to display in the DropDownList list, select CategoryName. Note
  • 57. If no items appear in the list, click the Refresh Schema link. 19. This specifies that the value of the CategoryName field will be displayed as the text of the item in the drop-down list. 20. From the Select a data field for the value of the DropDownList list, select CategoryID. This specifies that when an item is selected, the CategoryID field will be returned as the value of the item. 21. Click OK. Before proceeding, test the drop-down list. To test the drop-down list 1. Press CTRL+F5 to run the page. 2. When the page is displayed, examine the drop-down list. 3. Select a category to be sure that the list performs a postback. You can now display products for the category selected in the drop-down list. Using a Grid to Display Detail Information You can now extend the page to include a grid. When users make a selection from the categories drop- down list, the grid will display the products for that category. To use a grid to display detail information 1. Switch to or open the Default.aspx page (or the page you have been working with), and switch to Design view. 2. From the Data group of the Toolbox, drag a GridView control onto the page. 3. From the GridView Tasks menu, select <New Data Source> from the Choose Data Source list. The Data Source Configuration Wizard opens. 4. Select Database. In the Specify an ID for the data source box, a default data source control name is displayed (SqlDataSource2). You can leave this name. 5. Click OK. The wizard displays a page where you can select a connection. 6. From the connections drop-down list, select the connection you created and stored earlier in the walkthrough (NorthwindConnectionString). 7. Click Next. The wizard displays the Configure Data Source - SqlDataSource2 page in which you can create a SQL statement. 8. From the Name list, select Products. 9. In the Columns box, select ProductID, ProductName, and CategoryID. 10. Click WHERE. The Add WHERE Clause dialog box is displayed. 11. From the Column list, select CategoryID. 12. From the Operator list, select =. 13. From the Source list, select Control. 14. Under Parameter Properties, in the Control ID list, select DropDownList1. The last two steps specify that the query will get the search value for the category ID from the DropDownListcontrol you added earlier. 15. Click Add. 16. Click OK to close the Add WHERE Clause dialog box. 17. Click Next.
  • 58. 18. In the Preview page, click Test Query. The wizard displays a dialog box that prompts you for a value to use in the WHERE clause. 19. Type 4 in the box and click OK. The products records for category 4 are displayed. 20. Click Finish to close the wizard. You can now test the master/detail display. To test the page 1. Press CTRL+F5 to run the page. When the page appears, products from the first item in the drop-down list are displayed. 2. Select a category from the list and confirm that the corresponding products appear in the grid. Displaying Master/Detail Data on the Same Page In this part of the walkthrough, you will display data from related tables in one page. The master table data is displayed in a grid where users can select individual rows. When they do, one or more detail records are displayed in a scrollable control elsewhere on the page. For illustration purposes, you will use the Northwind Categories table as the master table and the Products table as the details table. To display the master records 1. Add a new page to the Web site and name it MasterDetails2.aspx. 2. Switch to Design view. 3. Type Master/Detail Page in the page and format the text as a heading. 4. From the Data group of the Toolbox, drag a GridView control onto the page. 5. In the GridView Tasks menu, in the Choose Data Source list, click <New Data Source> and then use these steps to configure a data source for the GridView control: a. Select Database. b. Click OK. c. From the connection drop-down list, select the connection you created and stored earlier in the walkthrough (NorthwindConnectionString). d. Click Next. e. From the Name list, select Categories. f. In the Columns box, select CategoryID and CategoryName. g. Click Next and then click Finish. 6. Select the GridView control, and in the GridView Tasks menu, choose Edit Columns. The Fields dialog box is displayed. 7. Under Available Fields, open the Command Field node, choose Select, and then click Add to add it to theSelected Fields list. 8. In the Selected Fields list, choose Select, and then in the CommandField property grid, set its SelectTextproperty to Details. 9. Click OK to close the Fields dialog box. A new column with a Details hyperlink is added to the grid. 10. Select the GridView control and in the Properties window, be sure its DataKeyNames property is set toCategoryID. This specifies that when you select a row in the grid, ASP.NET can find the key of the currently displayed Categories record in a known location. The grid allows you to select an individual category. The next step is to add the DetailsView control that will display the detail records — the products associated with the selected category. The DetailsView control will use a different SQL query to get its data, so it requires a second data source control.
  • 59. To configure a query to display related records 1. Press ENTER to make space underneath the SqlDataSource1 control on the MasterDetails2.aspx page in Details view. 2. From the Data group of the Toolbox, drag a DetailsView control onto the page. 3. Configure it to use a second data source control using the following steps: a. From the Choose Data Source list, select <New Data Source>. b. Select Database. c. Click OK. d. In the connection drop-down list, click the connection you created and stored earlier in the walkthrough. e. Click Next. f. From the Name list under Table or View Options, select Products. g. In the Columns box, select ProductID, ProductName, and CategoryID. h. Click WHERE. The Add WHERE Clause dialog box is displayed. i. From the Column list, select CategoryID. j. From the Operator list, select =. k. From the Source list, select Control. l. Under Parameter Properties, in the Control ID list, select GridView1. The query for the second grid will get its parameter value from the selection in the first grid. m. Click Add and then click OK to close the Add WHERE Clause dialog box. n. Click Next. o. In the Preview page, click Test Query. The wizard displays a dialog box that prompts you for a value to use in the WHERE clause. p. Type 4 in the box and click OK. The products records for category 4 are displayed. q. Click Finish. 4. In the DetailsView Tasks menu, check Enable Paging. This will allow you to scroll through individual product records. 5. Optionally, in the Properties window, open the PagerSettings node and select a different Mode value. By default, you page through records by clicking a page number, but you can select options to use next and previous links. You can now test the combination of the master grid and the details view. To test the page 1. Press CTRL+F5 to run the page. 2. In the grid, select a category. The DetailsView control displays a product associated with that category. 3. Use the pager links in the DetailsView control to navigate to other products for the same category. 4. In the grid, select a different category. 5. Review the products for that category in the DetailsView control. Displaying Master/Detail Data on Separate Pages For the final part of the walkthrough, you will create another variation — displaying master and detail records on separate pages. The master records are again displayed in a grid that contains a hyperlink for
  • 60. each record. When users click the hyperlink, they navigate to a second page where they can view detail records in a DetailsView control that displays the complete Products record. To display the master records 1. Add a new page to the Web site and name it MasterCustomers.aspx. 2. Switch to Design view. 3. Type Customers in the page and format the text as a heading. 4. From the Data folder of the Toolbox, drag a GridView control onto the page. 5. From the GridView Tasks menu on the control, choose <New Data Source> from the Choose Data Sourcelist and then use the wizard to do the following: o Click Database. o Connect to the Northwind database (connection NorthwindConnectionString). o Retrieve the CustomerID, CompanyName, and City columns from the Customers table. 6. Optionally, on the GridView Tasks menu, select the Enable paging check box. 7. In the GridView Tasks menu, choose Edit Columns. The Fields dialog box is displayed. 8. Clear the Auto-Generate Fields check box. 9. Under Available Fields, choose HyperLink Field, click Add, and then set the following properties: Property Value Text Details DataNavigateUrlFields CustomerID This indicates that the hyperlink should get its value from theCustomerID column DataNavigateUrlFormatString DetailsOrders.aspx?custid={0} This creates a link that is hard-coded to navigate to the DetailsOrders.aspx page. The link also passes a query string variable named custid whose value will be filled using the column referenced in the DataNavigateUrlFields property. 10. Click OK to close the Fields dialog box. You can now create the details page that accepts a value from the master page. To create the details page 1. Add a new page to the Web site and name it DetailsOrders.aspx. 2. Switch to Design view. 3. Type Orders in the page and format the text as a heading. 4. From the Data folder of the Toolbox, drag a GridView control onto the page. 5. In the GridView Tasks menu on the control, select <New Data Source> from the Choose Data Source list 6. In the Select a data source type list, click Database and then click OK. 7. From the connection list, select the connection you created and stored earlier in the walkthrough (NorthwindConnectionString). 8. Click Next.
  • 61. The wizard displays a page where you can create a SQL statement. 9. From the Name list, select Orders. 10. In the Columns box, select OrderID, CustomerID, and OrderDate. 11. Click WHERE. 12. From the Columns list, select CustomerID. 13. From the Operators list, select =. 14. From the Source list, select QueryString. This specifies that the query will select records based on the value passed into the page with the query string. 15. Under Parameter Properties, in the QueryString field box, type custid. The query will get the customer ID value from the query string, which is created when you click a Details link in the MasterCustomers.aspx page. 16. Click Add. 17. Click OK to close the Add WHERE Clause dialog box. 18. Click Next, and then click Finish to close the wizard. 19. From the Standard node of the Toolbox, drag a Hyperlink control onto the page. Set its Text property toReturn to Customers and its NavigateUrl property to MasterCustomers.aspx. You can now test the related master-detail pages. To test the pages 1. Switch to the MasterCustomers.aspx page. 2. Press CTRL+F5 to run the page. 3. Click the Details link for a customer. The browser displays the DetailsOrders.aspx page with the order for the selected customer. Note that the URL in the browser's Address box is: DetailsOrder.aspx?custid=x where x is the ID of the customer you selected. 4. Click the Return to Customers link, select a different customer, and click the Details link again to test that you can view orders for any customer. Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control Other Versions
  • 62. Microsoft Visual Web Developer allows you to create data entry forms for updating records and inserting new ones into a database with only a few lines of code. By using a combination of a data source control that encapsulates data access and DetailsView and GridView controls that display records in an editable format, you can create a data entry page that allows users to edit existing records or insert new ones, all without any code. A Visual Studio project with source code is available to accompany this topic: Download. During this walkthrough, you will learn how to:  Create a data entry page.  Configure a data source control with information required to make database updates and inserts.  Use the DetailsView control to view individual records, change them, and insert new ones.  Use a GridView control to enable database modification from the data entry page. Prerequisites In order to complete this walkthrough, you will need:  Visual Studio or Visual Web Developer Express. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  Microsoft Data Access Components (MDAC) version 2.7 or later. If you are using the Microsoft Windows XP or Windows Server 2003 operating systems or later, you already have MDAC 2.7. However, if you are using the Microsoft Windows 2000 Server operating system, you might need to upgrade the MDAC already installed on your computer. To download the current MDAC version, see the Data Developer Center on the MSDN Web site.  Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site. Note If you need information about how to log on to the computer running SQL Server, contact the server administrator.  Permission to modify data in the sample Northwind database. Creating the Web Site and Page This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a new file system Web site 1. Open Visual Studio or Visual Web Developer Express.
  • 63. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). Connecting to SQL Server The next step is to establish a connection to the SQL Server database. To create a connection to a SQL Server database 1. In Server Explorer, right-click Data Connections, and then click Add Connection. If you are using Visual Web Developer Express, use Database Explorer. The Add Connection dialog box appears. o If the Data source list does not display Microsoft SQL Server (SqlClient), click Change, and in theChange Data Source dialog box, select Microsoft SQL Server. o If the Choose Data Source page appears, in the Data source list, select the type of data source you will use. For this walkthrough, the data source type is Microsoft SQL Server. In the Data provider list, click.NET Framework Data Provider for SQL Server, and the click Continue. Note If the Server Explorer tab is not visible in Visual Web Developer, in the View menu, click Server Explorer. If the Database Explorer tab is not visible in the Express edition, in the View menu, click Database Explorer. 2. In the Add Connection box, enter your server name in the Server Name box. 3. For the Log on to the server section, select the option that is appropriate to access the running the SQL Server database (integrated security or specific ID and password) and, if required, enter a user name and password. Select the Save my Password check box if you entered a password. 4. Under Select or enter a database name, enter Northwind. 5. Click Test Connection, and when you are sure that it works, click OK. Your new connection has been created under Data Connections in Server Explorer. Creating the Data Entry Page In this section, you will create a data entry page and configure a DetailsView control so that you can view employee data that is stored in the Employees table of the Northwind database. To handle the data access for the page, you will configure a SQL data source control. To create a data entry page and configure a DetailsView control 1. On the Website menu, click Add New Item. The Add New Item dialog box appears. 2. Under Installed Templates, click Visual C# or Visual Basic, and then select Web Form.
  • 64. 3. In the Name box, type EditEmployees.aspx. 4. Click Add. The EditEmployees.aspx page opens in Source view. 5. Switch to Design view. 6. Type Edit Employees, select the text, and then format the text as a heading. 7. In the Toolbox, from the Datagroup, drag a DetailsView control onto the page. 8. Right-click the DetailsView control, click Properties, and then set AllowPaging to true. This will allow you to page through individual employee entries when they are displayed. The next step is to create and configure a data source control that can be used to query the database. There are a number of ways to create a data source control, including dragging data elements from Server Explorer or Database Explorer onto the page. In this walkthrough, you will start with the DetailsView control and configure the data source control from there. To configure a data source control 1. Right-click the DetailsView control and click Show Smart Tag. 2. On the DetailsView Tasks menu, in the Choose Data Source box, click <New data source>. The Data Source Configuration Wizard dialog box appears. 3. Under Select a data source type, click Database. 4. Leave the default name of SqlDataSource1, and then click OK. The Configure Data Source wizard displays the Choose a connection page. 5. In the Which data connection should your application use to connect to the database? box, enter the connection that you created in "To create a connection to SQL Server," and then click Next. The wizard displays a page where you can choose to store the connection string in a configuration file. Storing the connection string in the configuration file has two advantages: o It is more secure than storing it in the page. o You can use the same connection string in multiple pages. 6. Select the Yes, save this connection as check box, and then click Next. The wizard displays a page where you can specify what data you want to retrieve from the database. 7. On the Configure the Select Statement page, select Specify columns from a table or view, and then in theName box, click Employees. 8. Under Columns, select the EmployeeID, LastName, FirstName, and HireDate check boxes, and then clickNext. 9. Click Test Query to preview the data, and then click Finish. You can now test the employee records display page. To test displaying the employee records 1. Press CTRL+F5 to run the page. The first employee record is displayed in the DetailsView control. 2. Click the page number links to see additional employee records. 3. Close the browser. Allowing Editing in a GridView Control At this point, you can view employee records, but you cannot edit them. In this section, you will add a GridViewcontrol and configure it so that you can edit individual records.
  • 65. Note The GridView control presents a list of records and allows you to edit them. However, it does not allow you to insert them. Later in this walkthrough, you will use the DetailsView control, which allows you to add new records. To support editing, you must configure the data source control you created earlier (SqlDataSource1) with SQL statements that perform updates. To add a GridView control to allow editing 1. In the Toolbox, from the Data group, drag a GridView control onto the page. 2. Right-click the GridView control, click Show Smart Tag, and then on the GridView Tasks menu, in theChoose Data Source box, click SqlDataSource1. 3. On the GridView Tasks menu, click Configure Data Source. 4. Click Next to advance to the Configure the Select Statement page of the wizard. 5. On the Configure the Select Statement page, click Advanced, select the Generate INSERT, UPDATE, and DELETE statements check box, and then click OK. This generates Insert, Update, and Delete statements for the SqlDataSource1 control based on the Select statement that you configured earlier. Note Alternatively, you could manually create the statements by selecting Specify a custom SQL statement or stored procedure and entering SQL queries. 6. Click Next, and then click Finish. The SqlDataSource control is now configured with additional SQL statements. Note You can examine the statements generated by the wizard by selecting the SqlDataSource control and viewing the DeleteQuery, InsertQuery, and UpdateQuery properties. You can also view the updated control properties by switching to Source view and examining the markup of the control. 7. On the GridView Tasks menu, select the Enable Paging and Enable Editing check boxes. Security Note
  • 66. User input in an ASP.NET Web page can include potentially malicious client script. By default, ASP.NET Web pages validate user input to make sure input does not include script or HTML elements. As long as this validation is enabled, you do not need to explicitly check for script or HTML elements in user input. For more information, see Script Exploits Overview. You can now test the editing of employee records. To test the editing in the GridView control 1. Press CTRL+F5 to run the page. The GridView control is displayed with the data in text boxes. 2. Choose a row in the GridView control and click Edit. 3. Make a change to the record, and then click Update. The updated data now appears in both the GridView control and the DetailsView control. 4. Close the browser. Allowing Editing, Deleting, and Inserting Using a DetailsView Control The GridView control allows you to edit records, but it does not allow you to insert data. In this section, you will modify the DetailsView control so that you can see records individually, as well as delete, insert, and update records. To use a DetailsView control to allow deleting, inserting, and updating 1. Right-click the DetailsView control and then click Show Smart Tag. 2. On the DetailsView Tasks menu, select the Enable Inserting, Enable Editing, and Enable Deleting check boxes. When you used the DetailsView control earlier in the walkthrough, the options for enabling editing, inserting, and deleting were not available. The reason is that the SqlDataSource1 control that the DetailsView control is bound to did not have the necessary SQL statements. Now that you have configured the data source control to include update statements, the update options are available on the DetailsView control. You can now test deleting, inserting, and updating in the DetailsView control. To test the updating, inserting, and deleting in the DetailsView control 1. Press CTRL+F5 to run the page. The DetailsView control displays an employee record. 2. In the DetailsView control, click Edit. The DetailsView control now displays the data in text boxes. 3. Make a change to the record, and then click Update. The updated record is displayed in the control. 4. In the DetailsView control, click New. The control now displays blank text boxes for each column. 5. Enter values for each column. The Employees table has an auto-increment key column, so the value for EmployeeID is assigned automatically when you save the record. 6. When you are finished, click Insert. The new record is added as the last record.
  • 67. Note Inserting a new record in the Employees table in this walkthrough will not generate any errors. However, when you work with production data, the tables might have constraints (such as a foreign key constraint) that you must be aware of when configuring the DetailsView control. 7. Use paging in the DetailsView control to navigate to the last record, and then click Delete. The new record is removed. Note As with inserting data, you must always be aware of any constraints that apply to the data row when configuring a DetailsView control to allow deletion. Walkthrough: Using the ObjectDataSource with an XML File Other Versions Many Web applications are built by using multiple tiers, with one or more components in the middle tier to provide data access. Creating a custom middle tier business object allows you to implement your own business logic. This walkthrough illustrates how to create a basic business object that you can use as a data source for ASP.NET Web Forms pages. During this walkthrough, you will learn how to:  Create a component that can return data to a Web page. The component uses an XML file for its data.  Reference the business object as a data source on a Web page.  Bind a control to the data returned by the business object.  Read and write data by using the business object. Prerequisites
  • 68. In order to complete this walkthrough, you will need:  Visual Web Developer (Visual Studio).  The .NET Framework. This walkthrough assumes that you have a general understanding of how to use Visual Web Developer. Creating the Web Site If you have already created a Web site in Visual Web Developer (for example, by following the steps in Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and go to the next section, "Creating an XML File for Business Data." Otherwise, create a new Web site and page. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Web Developer. 2. On the File menu, click NewWeb Site. The New Web Site dialog box appears. 3. Under Visual Studio installed templates, click ASP.NET Web Site. 4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site. For example, type the folder name C:WebSites. 5. In the Language list, click the programming language you prefer to work in. 6. Click OK. Visual Web Developer creates the folder and a new page named Default.aspx. Creating an XML File for Business Data In the following procedure, you will create a simple XML file for the business component data. To create the XML file 1. In Solution Explorer, right-click App_Data, and then click AddNew Item. Note Be sure you create the XML file in the App_Data folder. The App_Data folder has permissions set on it that will allow the Web page to read and write data to the XML file. 2. Under Visual Studio installed templates, click XML file. 3. In the Name box, type Authors.xml. 4. Click Add. A new XML file is created that contains only the XML directive. 5. Copy the following XML data, and then paste it into the file, overwriting what is already in the file. The XML file includes schema information that identifies the database structure of the data, including a primary-key constraint for the key. Note
  • 69. Business components can work with data in any way that is suitable for your application. This walkthrough uses an XML file. <?xml version="1.0" standalone="yes"?> <dsPubs xmlns="http://www.tempuri.org/dsPubs.xsd"> <xs:schema id="dsPubs" targetNamespace="http://www.tempuri.org/dsPubs.xsd" xmlns:mstns="http://www.tempuri.org/dsPubs.xsd" xmlns="http://www.tempuri.org/dsPubs.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas- microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="dsPubs" msdata:IsDataSet="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="authors"> <xs:complexType> <xs:sequence> <xs:element name="au_id" type="xs:string" /> <xs:element name="au_lname" type="xs:string" /> <xs:element name="au_fname" type="xs:string" /> <xs:element name="au_phone" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name="Constraint1" msdata:PrimaryKey="true"> <xs:selector xpath=".//mstns:authors" /> <xs:field xpath="mstns:au_id" /> </xs:unique> </xs:element> </xs:schema> <authors> <au_id>172-32-1176</au_id> <au_lname>West</au_lname> <au_fname>Paul</au_fname> <au_phone>408 555-0123</au_phone> </authors> <authors> <au_id>213-46-8915</au_id> <au_lname>Gray</au_lname> <au_fname>Chris</au_fname> <au_phone>415 555-0120</au_phone> </authors> </dsPubs> 6. Save the Authors.xml file, and then close it.
  • 70. Creating a Component The next step is to create a class to act as your business component. You will keep the component in the App_Codefolder of your Web site. In a real application, you can keep the component in any convenient store, including the global assembly cache. If your Web site does not already have a directory named App_Code, you must create one. To create an App_Code folder  In Solution Explorer, right-click the name of your Web site, click Add ASP.NET Folder, and then clickApp_Code. Note The folder must be named App_Code. You can now add the component to your site. To create the business component 1. In Solution Explorer, right-click the App_Code folder, and then click Add New Item. Note Be sure to create the new item in the App_Code folder. 2. The Add New Item dialog box appears. 3. Under Visual Studio installed templates, click Class. 4. In the Language box, click the programming language you prefer. 5. In the Name box, type BusinessObject. 6. Click Add. Visual Web Developer creates the new class file and opens the code editor. 7. Copy the following code, and then paste it into the file, overwriting what is already in the file. C# VB using System; using System.Web; using System.Data; namespace PubsClasses { public class AuthorClass { private DataSet dsAuthors = new DataSet("ds1"); private String filePath = HttpContext.Current.Server.MapPath
  • 71. ("~/App_Data/Authors.xml"); public AuthorClass() { dsAuthors.ReadXml (filePath, XmlReadMode.ReadSchema); } public DataSet GetAuthors () { return dsAuthors; } } } Note Make sure the value of the filePath variable references the name of the XML file that you created previously. When an instance of the class is created, it reads the XML file and translates it into a dataset. The class'sGetAuthors method returns the dataset. 8. Save the file. You must save the file for the next section to work properly. Displaying Data by Using the Business Component You can now invoke the business component in a Web page and display its data. To reference the component, you use an ObjectDataSource control, which is specifically designed to work with objects. To create an ObjectDataSource control that references the component 1. Switch to or open the Default.aspx page. Note If you do not have a Default.aspx page, you can use another page. Alternatively, you can add a new page to the Web site. In Solution Explorer, right-click the name of your Web site, click Add New Item, and then add a Web Form. 2. Switch to Design view. 3. In the Toolbox, from the Data folder, drag an ObjectDataSource control onto the page. 4. In the Properties window, set ID to AuthorsObjectDataSource. 5. Right-click the ObjectDataSource control, and then click the smart tag to display the ObjectDataSource Tasks menu. 6. On the ObjectDataSource Tasks menu, click Configure Data Source. The Configure Data Source wizard appears. 7. In the Choose your business object list, click PubsClasses.AuthorClass. 8. Click Next. 9. In the Select tab, in the Choose a method list, click GetAuthors(), returns Dataset.
  • 72. The GetAuthors method is defined in the business class you created previously. It returns a dataset containing the data from the Authors.xml file. 10. Click Finish. The configuration information you have entered specifies that to get data from the component, the component's GetAuthors method should be called. Note The name of the method you specify for the SelectMethod property is case-sensitive, even if you are programming in Visual Basic .NET. You can now get data from the component by using the ObjectDataSource control. You will display the data in aGridView control on the page. To display data from the component 1. In the Toolbox, from the Data folder, drag a GridView control onto the page. 2. Right-click the GridView control, and then click the smart tag if the Common GridView Tasks menu is not showing. 3. On the Common GridView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource. 4. Press CTRL+F5 to run the page. The GridView control with the XML data in it is displayed. Inserting Data by Using the Business Component As with other data source controls, such as the SqlDataSource control, the ObjectDataSource control supports updating (inserting, updating, and deleting). In this section, you will modify the business component with a method that inserts an author record. Then you will change the page so that users can type new author information and modify the ObjectDataSource control to perform the insertion. Note During this part of the walkthrough, the Authors.xml file you created previously will be updated. It is important that the application have permission to write to the file at run time or the Web page will display an error when you try to update the file. If you created the Authors.xml file in the App_Data folder, permissions are set automatically. To modify the business component to allow inserts 1. Switch to the BusinessObject file. 2. Add the following method as the final member of AuthorClass. C# VB
  • 73. public void InsertAuthor (String au_id, String au_lname, String au_fname, String au_phone) { DataRow workRow = dsAuthors.Tables[0].NewRow (); workRow.BeginEdit (); workRow[0] = au_id; workRow[1] = au_lname; workRow[2] = au_fname; workRow[3] = au_phone; workRow.EndEdit (); dsAuthors.Tables[0].Rows.Add (workRow); dsAuthors.WriteXml (filePath, XmlWriteMode.WriteSchema); } Note Pay close attention to the names of the variables used to pass author information into the method (au_id,au_lname, au_fname, and au_phone). They must match the column names defined in the schema of the XML file you created previously. The new method takes four values to insert, which you will provide in the page as parameters. The method creates a new row in the dataset, and then writes the updated dataset out as an XML file. 3. Save the file. The next step is to change the page so that users can enter new author information. For the following procedure, you will use the DetailsView control. To add a control for inserting data 1. Switch to or open the Default.aspx page. 2. Switch to Design view. 3. In the Toolbox, from the Data folder, drag a DetailsView control onto the page. Note The exact layout of the page is not important. 4. On the DetailsView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource. Note If the DetailsView Tasks menu is not visible, click the smart tag.
  • 74. 5. In the Properties window, set AutoGenerateInsertButton to true. This causes the DetailsView control to render a New button that users can click to put the control into data-entry mode. Finally, you must configure the ObjectDataSource control to specify what action the control should take to insert data. To configure the data source control for inserting data  Right-click AuthorsObjectDataSource, click Properties, and then set InsertMethod to InsertAuthor. This is the name of the method that you added to the business component. You can now insert new authors into the XML file. To test insertion 1. Press CTRL+F5 to run the Default.aspx page. 2. In the DetailsView control, click the New button. The control is redisplayed with text boxes. 3. Enter new author information, and then click Insert. The new author information is added to the XML file. The GridView control immediately reflects the new record. Walkthrough: Debugging Web Pages in Visual Web Developer Other Versions Visual Studio provides you with tools to help track down errors in your ASP.NET Web pages. In this walkthrough, you will work with the debugger, which allows you to step through the page's code line by line and examine the values of variables. In the walkthrough, you will create a Web page that contains a simple calculator that squares a number. After creating the page (which will include a deliberate error), you will use the debugger to examine the page as it is running. Tasks illustrated in this walkthrough include:  Setting breakpoints.  Invoking debugger from a Web Forms page in a file system Web site. Prerequisites In order to complete this walkthrough, you will need:  Microsoft Visual Studio or Microsoft Visual Web Developer Express and the .NET Framework. You should also have a general understanding of working in Visual Studio. For an introduction to Visual Studio, seeWalkthrough: Creating a Basic Web Forms Page in Visual Studio. Creating the Web Site and Page
  • 75. In the first part of the walkthrough, you will create a page that you can debug. If you have already created a Web site in Visual Studio (for example, by working with the topic Walkthrough: Creating a Basic Web Forms Page in Visual Studio ), you can use that Web site and skip to "Adding Controls to Debug" later in this walkthrough. Otherwise, create a new Web site and page. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Studio. 2. On the File menu, click NewWeb Site. The New Web Site dialog box appears. 3. Under Visual Studio installed templates, click ASP.NET Web Site. 4. In the Location box, click File System and then type the name of the folder where you want to keep the pages of your Web site. For example, type the folder name C:WebSites. 5. In the Language list, click the programming language that you prefer to work in. The programming language you choose will be the default for your Web site. However, you can use multiple languages in the same Web application by creating pages and components in different programming languages. For information on creating components using different languages, see Shared Code Folders in ASP.NET Web Site Projects. 6. Click OK. Visual Studio creates the folder and a new page named Default.aspx. Creating a Page to Debug You will begin by creating a new page. For this walkthrough, it is important that you create a new page as specified in the following procedure. To add a page to the Web site 1. Close the Default.aspx page. 2. In Solution Explorer, right-click the name of your Web site (for example, C:WebSite) and choose Add New Item. 3. Under Visual Studio installed templates, choose Web Form. 4. In the Name box, type DebugPage.aspx. 5. From the Language list, choose the programming language you prefer to use. 6. Be sure that the Place code in separate file check box is cleared. In this walkthrough, you are creating a single-file page with the code and HTML in the same page. The code for ASP.NET pages can be located either in the page or in a separate class file. To learn more about keeping the code in a separate file, see Walkthrough: Creating a Basic Web Forms Page with Code Separation in Visual Studio . 7. Click Add. Visual Studio creates the new page and opens it in Source view. You can now add some controls to the page and then add code. The code will be simple, but enough to allow you to add breakpoints later. To add controls and code for debugging 1. Switch to Design view, and then from the Standard folder of the Toolbox, drag the following controls onto the page and set their properties as indicated: Control Properties
  • 76. Label ID: CaptionLabel Text: (empty) TextBox ID: NumberTextBox Text: (empty) Button ID: SquareButton Text: Square Label ID: ResultLabel Text: (empty) Note For this walkthrough, the layout of the page is not important. 2. Double-click the Button control to create a Click handler for it. 3. Add logic to the Click handler to call a function called Square to square the number entered by the user. The handler might look like the following example. Note The code example deliberately does not include error checking. 4. C# 5. VB 6. protected void SquareButton_Click(object sender, System.EventArgs e) 7. { 8. int number, result; 9. number = System.Convert.ToInt32(NumberTextBox.Text); 10. result = Square(number); 11. ResultLabel.Text = NumberTextBox.Text + 12. " squared is " + result.ToString(); 13. } 14. Create the function that squares the number. Include a bug in the code to add the number to itself instead of multiplying it. The code might look like the following example. C#
  • 77. VB int Square(int number ) { int Square; Square = number + number; return Square; } You can also add code to the page that will change the text of the label depending on whether this is the first time the page is running. To change the caption Label control 1. In Design view, double-click the design surface (not a control) to create a Page_Load event handler. 2. Set the text of the Caption Label control to Enter a number: if this is the first time the page is running, orEnter another number: otherwise. The handler will look like the following code example. C# VB if(Page.IsPostBack == false) { CaptionLabel.Text = "Enter a number: "; } else { CaptionLabel.Text = "Enter another number: " ; } Testing the Page To make sure the page is working, run it in its current state. To run the page 1. Save the page. 2. Press CTRL+F5 to run the page. 3. Enter the number 3 and press the Square button. Note that the result is incorrect, because there is a bug in the program. The correct result is 9. 4. Close the browser. Debugging the Page In this part of the walkthrough, you will use the debugger to examine the page code line by line as it is running, add breakpoints to the code, and then run the page in Debug mode. You will start by setting breakpoints in your code. A breakpoint is a line in your code where execution stops and the debugger is invoked. To set breakpoints 1. Switch to Source view. 2. Right-click the following line, choose Breakpoint, and then choose Insert Breakpoint.
  • 78. Note You can toggle breakpoints by pressing F9. 3. C# 4. VB 5. if(Page.IsPostBack == false) 6. Set another breakpoint on the following line of the SquareButton_Click handler: C# VB result = Square(number); Note You cannot set a breakpoint on a statement that declares a variable. With at least one breakpoint set, you are ready to run the debugger. To run the debugger 1. From the Debug menu, choose Start Debugging (or press F5) to run the page in debug mode. If you have never run the debugger before, your application probably is not configured to support debugging. By default, debugging is turned off in applications both for performance (pages run more slowly in the debugger) and for security reasons. Visual Studio displays a message telling you what it must do to enabled debugging. The switch to enable debugging is stored as a setting in the Web.config file, which maintains various site-specific configuration options. If the Web.config file does not exist, Visual Studio will both create the file and make the appropriate debugger setting. If the Web.config file already exists but debugging is not enabled, you will see a slightly different message telling you that Visual Studio will modify the Web.config file. 2. If you see the message telling you that debugging has not been enabled, click OK to enable debugging. In Visual Studio, the designer changes to debug mode displaying the code for your page and some debugger windows. The debugger runs your page line by line. When the debugger gets to the line with the breakpoint, it stops and highlights the line. Because the breakpoint is in the Page_Load handler, the page has not finished processing yet. The browser is open, but the page is not yet displayed. 3. In the Debug menu, click Windows, click Watch, and then click Watch 1.
  • 79. Note If you are using Visual Web Developer Express, the debugger offers only a single Watch window. 4. This opens a Watch window, where you can specify the values you want to track. 5. In the editor, right-click the IsPostBack portion of the Page.IsPostBack expression, and then clickAdd Watch. This adds the expression to the Watch window and displays the current value of the property (false) is displayed in the Value column. If you prefer, you can type the name of a variable or property in the Namecolumn of the Watch window. 6. From the Debug menu, choose Continue to continue execution, or press F5. The Continue command tells the debugger to proceed until it gets to the next breakpoint. The Page_Loadevent handler finishes processing and the page is displayed in the browser. 7. Enter the value 2 into the text box and click the Square button. The debugger is displayed again, with the breakpoint on the line in the Page_Load handler. This time, theWatch window shows you that the value of Page.IsPostBack is true. 8. Press F5 again to continue. The debugger processes the Page_Load handler and enters the SquareButton_Click handler, where it stops on the second breakpoint you set. 9. In the Debug menu, click Windows and then click Locals. This opens the Locals window, which displays the values of all variables and objects that are in scope at the current line being executed. The Locals window provides an alternative way for you to view these values, with the advantage that you do not have to explicitly set a watch on the elements, but with the disadvantage that the window might contain more information than you want to see at once. In the Locals window, you see that the value of number is 2 and the value of result is 0. Note You can also see the value of any variable in the program by holding the mouse pointer over it. 10. In the Value column of the Locals window, right-click the line for the number variable and select Edit value. Edit the value of the number variable and change it to 5. The value 2 for the variable number is not a good test of the program, because adding and squaring 2 both result in 4. Therefore, while the program is running, you can change the value of this variable. 11. From the Debug menu, choose Step Into to step into the Square function, or press F11. The Step Into command causes the debugger to execute a line and then stop again. 12. Continue stepping by pressing F11 until you reach the following line of code.
  • 80. C# VB ResultLabel.Text = NumberTextBox.Text + " squared is " + result.ToString(); The debugger walks through your code line by line. When the debugger executes the Square function, you can use the Locals window to check the data passed to the function (number) and the return value of the function (Square). 13. In the Debug menu, click Windows and then Immediate. The Immediate window allows you to execute commands. You can use the window to evaluate expressions (for example, to get the value of a property). 14. In the Immediate window, type the following expression and press Enter. 15. ? NumberTextBox.Text The question mark (?) is an operator in the Immediate window that evaluates the expression following it. In this example, you are evaluating the Text property of the NumberTextBox control on the page. You can evaluate any variable, object property, or expression that combine these, using the same syntax that you would use in code. 16. In the Immediate window, type the following and press Enter: 17. NumberTextBox.Text = "5" In addition to evaluating expressions, the Immediate window allows you to change variables or properties 18. Press F5 to continue running the program. When the page appears, it displays the result of passing 5 to the Square function. In addition, the text in the text box has been changed to 5. The result you see — 10 — is not correct, since 10 is not the square of 5. You can now fix the bug. To fix the bug and test again 1. Switch from the browser to Visual Studio. Note Do not close the browser window. 2. In the Square function, change the "+" operator to the "*" operator. Because the code is not currently running (the page has finished processing), you are in edit mode and can make permanent changes. 3. Press CTRL+S to save the page. 4. From the Debug menu, choose Delete All Breakpoints so that the page will not stop each time you run it. Note
  • 81. You can also clear breakpoints by pressing CTRL+SHIFT+F9. 5. Switch to the browser window. 6. Enter 5 in the text box and click the button. This time, when you run the page and enter a value, it is squared correctly. The temporary changes you made earlier, such as changing the Text property of the NumberTextBox control, have not been persisted, because they applied only when the page was running the last time. 7. Close the browser to stop the debugger. Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer Other Versions This walkthrough illustrates how to create a master page and several content pages. Master pages allow you to create a page layout — a template page — and then create separate pages containing content that is merged with the master page at run time. For more information about master pages, see ASP.NET Master Pages. A Visual Studio project with source code is available to accompany this topic: Download. Note By default, the ASP.NET Web Site project template includes prebuilt functionality, which includes a master page. However, this walkthrough uses the ASP.NET empty Web site project template to show you how to manually add a master page to a Web site. Tasks illustrated in this walkthrough include:  Creating a master page.  Creating an ASP.NET page that contains content that you want to display in the master page.  Selecting a master page at run time. Prerequisites In order to complete this walkthrough, you will need:  Visual Studio or Microsoft Visual Web Developer Express.
  • 82. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  Optionally, a .jpg, .gif, or other graphics file that you can use as a logo on your master page. It is recommended that the logo be no more than 48 pixels wide. However, displaying a logo is optional and the graphic's exact size is not critical to the walkthrough. Creating a Web Site If you have already created a Web site in Visual Web Developer (for example, by following the steps in Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and skip to the next section, Creating the Master Page. Otherwise, create a new Web site and page. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Studio or Visual Web Developer Express. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or VisualC# and then select ASP.NET Empty Web Site. 4. In the Weblocation box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates an Web site project that includes a Web.config file. Creating the Master Page The master page is the template for how your pages will look. In this section, you will first create a master page. You will then use a table to lay out the master page with a menu, a logo, and a footer that will appear on each page of your site. You will also work with a content placeholder, which is a region in the master page that can be replaced with information in a content page. To create the master page 1. In Solution Explorer, right-click the name of your Web site, and then click AddNew Item. 2. Under Visual Studio installed templates, click Master Page. 3. In the Name box, type Master1. 4. Select the Place code in separate file check box. Note
  • 83. This walkthrough assumes you are using code-behind files for all pages. If you are using a single-file ASP.NET page, the code illustrated in this walkthrough will work, but will appear in Source view, not in a separate code file. 5. In the Language list, click the programming language you prefer and then click Add. The new master page opens in Source view. At the top of the page is an @ Master declaration instead of the @ Page declaration normally found at the top of ASP.NET pages. The body of the page contains a ContentPlaceHolder control, which is the area of the master page where replaceable content will be merged from content pages at run time. You will work more with the content placeholder later in this walkthrough. Laying Out the Master Page The master page defines how the pages in your site look. It can contain any combination of static text and controls. A master page also contains one or more content placeholders that designate where dynamic content will appear when pages are displayed. In this walkthrough, you will use a table to help you position elements on the page. You will start by creating a layout table to hold the master page elements. Later in this section you will position the content placeholder control that is already on the page. To create a layout table for the master page 1. With the Master1.master file selected in Source view, use the Target Schema for Validation drop-down list on the toolbar to set the target schema to Microsoft Internet Explorer 6.0. 2. Switch to Design view. 3. Click on the center of the page to select the page. From the Properties window, set BgColor property to a distinctive color, such as blue. The color you select is not important. Later in this walkthrough you will create a second master page without a color to contrast with what you have selected here. 4. Click the page where you want to place the layout table. Note Do not put the layout table inside the ContentPlaceHolder control. 5. On the Table menu, click Insert Table. 6. In the Insert Table dialog box, create a table with three rows and one column, and then click OK. 7. Place the cursor inside the second row of the table. 8. On the Table menu, in the Modify submenu, click Split Cells. 9. In the Split Cells dialog box, select Split into columns, and then click OK. 10. Make the following settings: o In the middle row, click the leftmost column, and then set its Width to 48 in the Properties window. o Click the top row, and then set its Height to 48 in the Properties window. o Click the bottom row, and then set its Height to 48 in the Properties window.
  • 84. Note You can set the width and height by dragging the table cell borders or by selecting the cell and setting values in the Properties window. 11. Select all cells in the table and set BgColor to a different color than the background color. After laying out the table, you can add content to the master page that will appear on all pages. You will add a copyright message as a footer, and then add a menu. If you have a logo graphic available, you can add that as well. To add static content to the master page 1. Click the bottom cell, and then type footer text such as Copyright 2007 Contoso Inc. 2. In the Toolbox, from the Navigation control group, drag a Menu control into the top cell. 3. Create a menu by following these steps: a. Set the Menu control's Orientation property to Horizontal. b. Click the smart tag on the Menu control, and click Edit Menu Items in the Menu Tasks dialog box. TheEdit Menu Items dialog box appears. 4. In the Edit Menu Items dialog box, in the Items section, click the Add a root node icon twice to add two menu items: a. Click the first node, and then set Text to Home and NavigateUrl to Default.aspx. b. Click the second node, and then set Text to About and NavigateUrl to About.aspx. c. Click OK to close the Menu Item Editor dialog box. 5. If you have a graphics file available to use as a logo, follow these steps to place it on the master page: a. In Solution Explorer, right-click the name of your Web site, and then click Add Existing Item. b. Navigate to your graphics file, select the graphic file, and then click Add. c. In the Toolbox, from the Standard group, drag an Image control to the middle left column of the table. d. Set the Image control's ImageUrl property to the name of the graphics file. You can now position the content placeholder to specify where the master page can display content at run time. To move the content placeholder 1. Drag the ContentPlaceHolder control into the middle right cell. You can move the control by clicking inside the control and then dragging it by its tag. The control's ID property is ContentPlaceholder1. You can leave this name or change it. If you change the name, make a note of the name because you will need to know the name later. 2. Save the page. Creating Content for the Master Page The master page provides the template for your content. You define content for the master page by creating an ASP.NET page that is associated with the master page. The content page is a specialized form of an ASP.NET page that contains only the content to be merged with the master page. In the content page, you add the text and controls that you want to display when users request that page.
  • 85. In this walkthrough, you will add two pages with content for the master page. The first is a default (home) page and the second is an about page. To create the Default page 1. In Solution Explorer, right-click the name of your Web site, and click Add New Item. 2. Under Visual Studio installed templates, click Web Form. 3. In the Name box, keep the file name that Visual Studio inserts: Default. 4. In the Language list, click the programming language you prefer. 5. Select the Select master page check box, and then click Add. The Select a Master Page dialog box appears. 6. Click Master1.master, and then click OK. A new .aspx file is created. The page contains an @ Page directive that attaches the current page to the selected master page with the MasterPageFile attribute, as shown in the following code example. C# VB <%@ Page Language="C#" MasterPageFile="~/Master1.master" ... %> The page also contains an Content control element that you will work with next. A content page does not have the usual elements that make up an ASP.NET page, such as html, body, or formelements. Instead, you add only the content that you want to display on the master page by replacing the placeholder regions you created in the master page. To add content to the Default page 1. In Source view, type Contoso Home Page in the Title element of the @ Page directive at the top of the page. You can set the title of each content page independently, so that the correct title is displayed in the browser when the content is merged with the master page. The title information is stored in the content page's@ Page directive. 2. Switch to Design view. The ContentPlaceHolder controls in the master page are displayed as Content controls in the new content page. The rest of the master page content is displayed so that you can see the layout. However, it appears dimmed because you cannot change it while you are editing a content page, and the cursor becomes the I-bar only where you can add content. 3. In the Content control that matches ContentPlaceHolder1 on the master page, type Welcome to the Contoso Web Site. 4. Select the text then format it as a heading by selecting Heading 1 from the Block Format drop- down list above the Toolbox. 5. Press ENTER to create a new blank line in the Content control, and then type Thank you for visiting our site. The text you add here is not important; you can type any text that will help you recognize this page as the Default (home) page. 6. Save the page. You can create the About page the same way you created the Default page. To create the About page
  • 86. 1. Use the same steps that you used for the Default page to add a new content page named About.aspx. Be sure to attach the new page to the Master1.master page as you did with the Default page. 2. Change the page's title to Contoso About Page. 3. In the content region, type About Contoso, and then format the text as a Heading 2 by selecting the text and selecting Heading 2 from the Block Format drop-down list above the Toolbox. 4. Press ENTER to create a new line, and then type Since 1982, Contoso has provided high-quality software services. 5. Save the page. Testing the Pages You can test the pages by running them as you would any ASP.NET page. To test the pages 1. Switch to the Default.aspx page, and then press CTRL+F5. ASP.NET merges the content in the Default.aspx page with the layout in the Master1.master page into a single page and displays the resulting page in the browser. 2. Click the About link. The About.aspx page is displayed. It is also merged with Master1.master page. Referencing Master Page Members Code in the content pages can reference members on the master page, including any public properties or methods and any controls on the master page. In this part of the walkthrough, you will create a property on the master page, and then use the value of the property in the content pages. The premise is that the company name for the Web site is stored as a property in the master page, and any reference to the company name in the content pages is based on the master page property. The first step is to add a property to the master page. To add a property to the master page 1. Switch to or open the Master1.master page. 2. In Solution Explorer, right-click Master1.master, and then click View Code to open the code editor. Note By default, Visual Web Developer creates pages that use the code-behind model. 3. Inside the class definition, type the following code. C# VB public String CompanyName { get { return (String) ViewState["companyName"]; } set { ViewState["companyName"] = value; } }
  • 87. The code creates a property named CompanyName for the master page. The value is stored in view state so that it is persisted between postbacks. 4. Inside the class definition (but not inside the property code), add the following code. C# VB void Page_Init(Object sender, EventArgs e) { this.CompanyName = "Contoso"; } For this example, you will hard-code the value of the CompanyName property into the page. You can now modify the content page to use the master page's CompanyName property. To reference the CompanyName property in the content page 1. Switch to or open the Default.aspx page. 2. Switch to Source view. 3. At the top of the page, underneath the @ Page directive, add the following @ MasterType directive: 4. <%@ MasterType virtualpath="~/Master1.master" %> The directive binds the content page's Master property, which you will use shortly, to the Master1.master page. 5. Switch to Design view. 6. In the Content control, change the text to Welcome to the Web site of . 7. In the Toolbox, from the Standard group, drag a Label control onto the Content control, and place it after the static text so that the text reads: Welcome to the Web site of [Label] 8. Set the Label control's ID property to CompanyName. 9. In Solution Explorer, right-click Default.aspx, and then click View Code to open the code editor. 10. Inside the class definition, add the following code. C# VB void Page_Load(Object sender, EventArgs e) { CompanyName.Text = Master.CompanyName; } The content page's Master property returns a reference to the master page as defined in the @ MasterTypedirective you added in step 3. You can now test the content page to be sure it is referencing the master page's CompanyName property correctly. To test the reference to the master page property 1. Switch to or open the Default.aspx page, and then press CTRL+F5 to run the page.
  • 88. The page is displayed in the browser, with the text Welcome to the Web site of Contoso 2. Close the browser. 3. Switch to or open the Master1.master code-behind page. 4. Change the Page_Init handler to assign a different company name to the property, as in the following code example. C# VB void Page_Init(Object sender, EventArgs e) { this.CompanyName = "New Company Name"; } 5. Switch to the Default.aspx page, and then press CTRL+F5 to run it again. This time, the updated company name appears in the page. Changing Master Pages Dynamically Under some circumstances, you might want to be able to change master pages dynamically; that is, to use code to set the master page for a content page. For example, you might want to let users select from several layouts and set the master page according to their preferences. In this part of the walkthrough, you will add a second master page to the Web site, and then create buttons that allow the user to switch between one master page and another. Because the two master pages will be very similar, you will make a copy of the first master page and modify it to act as the second master page. To make a copy of the master page 1. In Solution Explorer, right-click Master1.master, and then click Copy. 2. Right-click the name of the Web site, and then click Paste. A master page is added to the Web site with the name Copy of master1.master. 3. Right-click Copy of master1.master, click Rename, and then name the new master page Master2.master. 4. Open Master2.master and, in the @ Master directive, change Master1 to Master2. The completed page directive will look like the following code example: C# VB <%@ Master Language="C#" CodeFile="Master2.master.cs" Inherits="Master2" %> 5. Switch to Design view. 6. In the Properties window, in the drop-down list at the top, click DOCUMENT. 7. Change the BgColor property to a color visibly different than the color you chose for Master1. The new master page will look and function like Master1.master, but will have a different background color.
  • 89. 8. Open the code file for Master2.master and change the class name in the master page's code- behind file fromMaster1 to Master2 to match the value of the Inherits attribute in the page's @ Master directive. The code will look like the following example: C# VB public partial class Master2 : System.Web.UI.MasterPage The next step is to add a button to each master page that allows the user to select the alternate master page. To add buttons for selecting an alternate master page 1. Switch to or open the Master2.master page. 2. In the Toolbox, from the Standard node, drag a LinkButton control onto the page and place it below the menu in the top table cell. 3. Set the button's Text property to First Color. 4. Double-click the button to create a handler for its Click event, and then add the following highlighted code. C# VB protected void LinkButton1_Click(Object sender, EventArgs e) { Session["masterpage"] = "Master1.master";Response.Redirect(Request.Url.ToString()); } The code loads the file name of the alternate master page into a persistent session variable, and then reloads the current page. (The Url property returns a Uri object that references the current page.) Shortly, you will create code in the content page that will use the name of the master page. 5. Switch to or open the Master1.master page in Design view. 6. Add a LinkButton control as you did in steps 1 and 2, and set its Text property to Second Color. 7. Double-click the Plain button to create a handler for its Click event, and then add the following highlighted code. C# VB protected void LinkButton1_Click(Object sender, EventArgs e) { Session["masterpage"] = "Master2.master";Response.Redirect(Request.Url.ToString()); }
  • 90. This code is the same as that for the button in the Master2.master page, except that it loads an alternate master page. You can now write code in the content page that will dynamically load the master page that the user has selected. To write code to dynamically select the master page 1. Switch to or open the About.aspx page. Note The Default page you have already created contains an @ MasterType directive that effectively binds it to a single master page (Master1.master). Therefore, you will not be able to assign master pages dynamically to the Default page and will instead work with other pages you have created. 2. In Solution Explorer, right-click About.aspx, and then click View Code to open the code editor. 3. Inside the class definition, add the following code. C# VB void Page_PreInit(Object sender, EventArgs e) { if(Session["masterpage"] != null) { this.MasterPageFile = (String) Session["masterpage"]; } } The code sets the value of the current page's MasterPageFile property to the value in the session variable, if any. This code must run in the Page_PreInit handler; it cannot run in a handler that occurs any later than thePage_PreInit handler (for example, in the Page_Init handler), because the master page must be established so that the page can create an instance of it before any further initialization can occur. You can now test the dynamic master pages. To test the dynamic master pages 1. In the About.aspx page, press CTRL+F5 to run the page. The page is displayed in the browser merged with its default master page, Master1.master. 2. Click the Second Color link. The page is redisplayed, this time merged with Master2.master, which has no background color. 3. Click the First Color link. The page is displayed using Master1.master again. Notes on Using Master Pages There are several other issues you should be aware of when working with a master page:
  • 91.  In a real-world application, you would probably store information such as the company name in the configuration file and read it directly in the content pages. However, the scenario outlined here provides a simple illustration of how to reference master page members in content pages.  You can access members on the master page even without including an @ MasterType directive. However, to do so, you must cast the Page.Master property to the appropriate master page type (the Master property is null if a page has no master page). For more information, see Working with ASP.NET Master Pages Programmatically. You can reference controls on the master page by using the Master.FindControls method. For more information, see Working with ASP.NET Master Pages Programmatically. There are several other issues you should be aware of when working with dynamic master pages:  The scenario in this section for changing master pages is simplified to keep the walkthrough focused on master pages. In a real application, you would most likely display a choice of layouts, and then store the user's preference by using profiles. For details, see ASP.NET Profile Properties Overview.  You can configure your Web site so that all pages use the same master page. You might have a few pages that should use an alternate master page, which you can configure in code in a manner similar to that shown in this section of the walkthrough. For details, see "Scoping Master Pages" in ASP.NET Master Pages.  You need to add the code from the Default.aspx page to every page where you want to override the default master page. Walkthrough: Adding Site Navigation to a Web Site Other Versions In any site that has more than just several pages, it can be difficult to construct a navigation system that lets users move freely between pages, especially as you change the site. ASP.NET site navigation lets you create a centralized site map of the pages. This walkthrough shows you how to configure a site map and how to use controls that rely on the site map to add navigation to pages in the Web site. During this walkthrough, you will learn how to do the following:  Create a Web site that has example pages and a site-map file that describes the layout of the pages.  Use the TreeView control as a navigation menu that lets users jump to any page in your site.  Use the SiteMapPath control to add a navigation path, also known as a breadcrumb, that enables a user to view and move back up the site hierarchy from the current page.
  • 92.  Use the Menu control to add a navigation menu that lets users view one level of nodes at a time. Pausing the mouse pointer over a node that has child nodes generates a submenu of the child nodes.  Use site navigation and controls on a master page so that you have to define the site navigation only once. A Visual Studio Web site project with source code is available to accompany this topic: Download. Prerequisites In order to complete this walkthrough, you will need the following:  Microsoft Visual Web Developer Web development tool.  The .NET Framework. This walkthrough assumes that you know how to use Visual Web Developer. Creating a Web Site That Has Example Pages and a Site Map If you have already created a Web project in Visual Web Developer by completing Walkthrough: Creating a Basic Web Forms Page in Visual Studio, you can use that project and go to the next section. Otherwise, create a new Web site project and page by following these steps. Note This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. Creating a File System Web Site To create a file system Web site 1. Open Visual Web Developer. 2. On the File menu, click New Web Site (or on the File menu, click New, and then click Web Site). The New Web Site dialog box appears. 3. Under Visual Studio installed templates, click ASP.NET Web Site. 4. In the left-most Location box, click File System, and then in the right-most Location box, enter the name of the folder where you want to keep the pages of the Web site. For example, type the folder name C:WebSitesSiteNavigation. 5. In the Language box, click the programming language that you prefer to work in. The programming language that you choose will be the default for the Web site, but you can set the programming language for each page individually. 6. Click OK. Visual Web Developer creates the folder and a new page named Default.aspx. Creating a Site Map To use site navigation, you need a way to describe how the pages in your site are laid out. The default method is to create an .xml file that contains the site hierarchy, including the page titles and URLs. The structure of the .xml file reflects the structure of your site. Each page is represented as a siteMapNodeelement in the site map. The top-most node represents the home page, and child nodes represent pages that are deeper in the site.
  • 93. To create a site map 1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item. 2. In the Add New Item <Path> dialog box: a. Under Visual Studio installed templates, click Site Map. b. In the Name box, Make sure that the name is Web.sitemap. Note The file must be named Web.sitemap and must appear in the root of the Web site. c. Click Add. 3. Copy the following XML content into the Web.sitemap file, overwriting the default contents. 4. <siteMap> 5. <siteMapNode title="Home" description="Home" url="~/home.aspx" > 6. <siteMapNode title="Products" description="Our products" 7. url="~/Products.aspx"> 8. <siteMapNode title="Hardware" 9. description="Hardware we offer" 10. url="~/Hardware.aspx" /> 11. <siteMapNode title="Software" 12. description="Software for sale" 13. url="~/Software.aspx" /> 14. </siteMapNode> 15. <siteMapNode title="Services" description="Services we offer" 16. url="~/Services.aspx"> 17. <siteMapNode title="Training" description="Training" 18. url="~/Training.aspx" /> 19. <siteMapNode title="Consulting" description="Consulting" 20. url="~/Consulting.aspx" /> 21. <siteMapNode title="Support" description="Support" 22. url="~/Support.aspx" /> 23. </siteMapNode> 24. </siteMapNode> 25. </siteMap> The Web.sitemap file contains a set of siteMapNode elements that are nested to three levels. The structure of each element is the same. The only difference among them is the location within the XML hierarchy. The URL of the pages that are defined in the sample .xml file is unqualified. This means that all pages are treated as having URLs that are relative to the application root. However, you can specify any URL for a specific page — the logical structure that you define in the site map does not have to correspond to the physical layout of the pages in folders. 26. Save the file, and then close it. Creating Pages to Navigate
  • 94. In this section, you will create only a few of the pages that are described in the site map that you defined in the preceding section. (The site map is more complete so that you will be able to view a full hierarchy when testing the pages in this walkthrough.) To create pages to navigate 1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item. 2. In the Add New Item <Path> dialog box: a. Under Visual Studio installed templates, click Web Form. b. In the Name box, type Home.aspx, and then click Add. 3. Switch to Design view. 4. On the Home.aspx page, type Home, and then format it as a Heading 1. Repeat this procedure and create four additional pages named Products.aspx, Hardware.aspx, Software.aspx, and Training.aspx. Use the name of the page (for example, Products) as the heading so that you will be able to recognize each page when the page is displayed in the browser. It is not important which pages you specifically create. The pages that are listed in this procedure are suggestions that will let you see the site hierarchy nested to three levels. Creating a Navigation Menu Using the TreeView Control Now that you have a site map and some pages, you can add navigation to your site. You will use the TreeViewcontrol to act as a collapsible navigation menu. To add a tree-style navigation menu 1. Open the Home.aspx page. 2. From the Data group in the Toolbox, drag a SiteMapDataSource control onto the page. In its default configuration, the SiteMapDataSource control retrieves its information from the Web.sitemap file that you created in "Creating a Site Map," earlier in this walkthrough, so that you do not have to specify any additional information for the control. 3. From the Navigation group in the Toolbox, drag a TreeView control onto the page. 4. On the TreeView Tasks menu, in the Choose Data Source box, click SiteMapDataSource1. 5. Save the page. Testing the Tree Style Navigation Menu You can now perform an interim test of your navigation system. To test the navigation menu
  • 95. 1. Press CTRL+F5 to run the Home.aspx page. The tree shows two levels of nodes. 2. Click Products to view the Products page. o If you did not create a Products.aspx page, click the link for a page that you did create. In the current state of the Web site, the navigation menu appears only on the Home page. You could add the sameSiteMapDataSource and TreeView controls to each page in the application to display a navigation menu on each page. However, later in this walkthrough, you will see how to place the navigation menu on a master page so that the navigation menu automatically appears with every page. Displaying Navigation History Using the SiteMapPath Control Besides creating a navigation menu by using the TreeView control, you can add navigation on each page that displays where the page is in the current hierarchy. This kind of navigation control is also known as a breadcrumb. ASP.NET provides the SiteMapPath control that can automatically implement page navigation. To display navigation history 1. Open the Products.aspx page and switch to Design view. 2. From the Navigation group in the Toolbox, drag a SiteMapPath control onto the page, place the cursor in front of the SiteMapPath control, and then press ENTER to create a new line. The SiteMapPath control displays the position of the current page in the page hierarchy. By default, theSiteMapPath control represents the hierarchy that is created in the Web.sitemap file. For example, when you display the Products.aspx page, the SiteMapPath control displays the following path: Home > Products 3. Repeat this procedure for the other pages that you have created in this walkthrough, except the Home page. Even if you do not put a SiteMapPath control on each page, for testing purposes you need a control on a page at each level of the site hierarchy (for example, on the Products.aspx and Hardware.aspx pages). Testing Navigation History You can test page navigation by viewing pages that are at the second and third levels of the hierarchy. To test page navigation 1. Open the Home.aspx page, and then press CTRL+F5 to run the page. 2. Use the TreeView control to move to the Products page. At the location in the page where you put the SiteMapPath control, you see a path that is similar to the following: Home > Products 3. Click Home to return to the Home page. 4. Use the TreeView control to move to the Hardware page. This time you see a path that is similar to the following: Home > Products > Hardware All page names that are displayed by the SiteMapPath control are links, except the last one, which represents the current page. You can make the current node into a link by setting the RenderCurrentNodeAsLink property of theSiteMapPath control to true. The SiteMapPath control lets users move back up the site hierarchy, but it does not allow for them to jump to a page that is not in the current hierarchy path.
  • 96. Creating a Navigation Menu Using the Menu Control Besides creating a navigation menu by using the TreeView control, you can use the Menu control to display an expandable navigation menu that lets users view one level of nodes at a time. Pausing the mouse pointer over a node that has child nodes generates a submenu of the child nodes. To add a menu-style navigation menu 1. Open the Products.aspx page and switch to Design view. 2. From the Navigation group in the Toolbox, drag a Menu control onto the page. 3. On the Menu Tasks menu, in the Choose Data Source box, click NewDataSource. 4. In the Configure Data Source — <Datasourcename> wizard, click Site Map, and then click OK. 5. Save the page. Testing the Menu Style Navigation Menu You can now perform an interim test of your navigation system. To test the navigation menu 1. Close Menu Tasks. 2. Open the Home.aspx. 3. Press CTRL+F5 to run the Home.aspx page. The tree shows two levels of nodes. 4. Click Products to view the Products page. o If you did not create a Products.aspx page, click the link for a page that you did create. 5. On the navigation menu, rest the mouse pointer on the Home link to expand the menu. In the current state of the Web site, the navigation menu appears only on the Home page. You could add the sameSiteMapDataSource and Menu controls to each page in the application to display a navigation menu on each page. However, in the next section of this walkthrough, you will see how to put the navigation menu on a master page so that it automatically appears with each page. Combining Site Navigation with Master Pages In the pages that you have created up to this point in this walkthrough, you have added site navigation controls individually to each page. Doing this is not especially complex, because you do not have to configure the controls differently for each page. However, it can add to the maintenance costs for your site. For example, to change the location of the SiteMapPath control for pages in your site, you would have to change each page individually. By using site navigation controls in combination with master pages, you can create a layout that contains the navigation controls in one location. You can then display pages as content within the master page. To create the master page for navigation 1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item. 2. In the Add New Item <Path> dialog box: a. Under Visual Studio installed templates, click Master Page. b. In the Name box, type Navigation.master, and then click Add. 3. Switch to Design view. The master page appears with a default ContentPlaceHolder control. In the following procedure, you will create a master page with a simple layout for navigation controls. In a real application, you would likely use more sophisticated formatting, but the techniques for using navigation controls on a master page will be similar. To add navigation controls to the master page 1. Select the ContentPlaceHolder control, press LEFT ARROW, and then press ENTER. This inserts a blank line in front of the ContentPlaceHolder control.
  • 97. 2. From the Data group in the Toolbox, drag a SiteMapDataSource control onto the master page and position it above the ContentPlaceHolder control. Note Do not position the SiteMapDataSource control on the ContentPlaceHolder control. 3. By default, the SiteMapDataSource control will use the Web.sitemap file that you created in "Creating a Site Map," earlier in this walkthrough. 4. Click the SiteMapDataSource control, press RIGHT ARROW, and then press ENTER. This inserts a blank line under the SiteMapDataSource control. 5. On the Table menu, click Insert Table, and then insert a table that has one row, two columns, and a width of 100 percent. 6. From the Navigation group in the Toolbox, drag a TreeView control onto the left cell of the table. 7. On the TreeView Tasks menu, in the Choose Data Source box, click SiteMapDataSource1. 8. From the Navigation group in the Toolbox, drag a SiteMapPath control onto the right cell of the table. 9. In the right cell, click the blank area, and then press SHIFT+ENTER to create a new line. 10. Drag the ContentPlaceholder control onto the right cell of the table and position it under the SiteMapPathcontrol. When you are using a master page, you create the pages in your site as content pages. The content pages useContent controls to define the text and controls that are displayed in the ContentPlaceHolder control of the master page. Therefore, you will have to re-create the Home, Products, and Hardware pages as content pages. To create content pages for the site 1. In Solution Explorer, right-click the Home.aspx page, click Delete, and then click OK. 2. Repeat step 1 for the Products.aspx, Software.aspx, Training.aspx, and Hardware.aspx pages, and any other pages you have created. You will re-create the pages as content pages that use a master page. 3. In Solution Explorer, right-click the name of the Web site, and then click Add New Item. 4. In the Add New Item dialog box: a. Under Visual Studio installed templates, click Web Form. b. In the Name box, type Home.aspx. c. Select the Select master page check box. d. Click Add. The Select a Master Page dialog box appears. 5. Under Contents of folder, click Navigation.master, and then click OK. You have created a content page that is bound to the master page that you created in the preceding section. 6. Switch to Design view. In Design view, you see the layout that you created for the master page, with an editable region corresponding to the ContentPlaceHolder1 control on the master page. 7. Click inside the Content window. This is where you can add content for this specific page.
  • 98. 8. Type Home, and then format the text as Heading 1. You have created the static text (specifically, the heading) for the Home page. 9. Repeat steps 3 through 8 to create a Products.aspx content page and a Hardware.aspx content page. In step 8, type Products and Hardware, respectively, instead of Home. Testing Navigation Controls in the Master Page Testing with master pages and content pages is the same as testing individual pages. To test navigation controls in the master page 1. Open the Products.aspx page, and then press CTRL+F5 to run the page. The Products content page is merged with the master page. In the browser, you see a page that contains the Products heading and the navigation controls that you added to the master page. 2. In the TreeView control, click Hardware. The Hardware page is displayed with the same layout as the Products page, except that the SiteMapPathcontrol displays a different path. Next Steps This walkthrough illustrates the basic functionality of ASP.NET site navigation and the navigation controls. You might want to experiment with additional features of navigation. For example, you might want to do the following:  Format the SiteMapPath control to customize its appearance. The control supports many options that manage how the links are displayed. For more information, see SiteMapPath.  Customize the display of the pages in the TreeView control. For example, you might highlight the current page in the tree view node.  Work programmatically with the site-navigation information. A SiteMapPath control is available on the current page, which you can use to programmatically display navigation information.  Use a different data store for the site-map information. Instead of using the default XML site-map file, you might want to use an existing site map or store site-map information in a database. ASP.NET site navigation uses a provider model. You can create a component that manages site- map information, and then configure your application to use that component instead of the default site-map provider. For more information, seeASP.NET Site Navigation Providers. Testing Web Pages in Visual Studio .NET Framework 4.5 Other Versions Visual Studio provides you with various ways to test web pages as you are developing them. You have the following choices:
  • 99.  Start Debugging (F5). This option runs the web project in the browser and allows you to perform debugging tasks such as stepping through code and stopping at breakpoints.  Start Without Debugging (CTRL+F5). This option runs the web project in the browser without using the debugger. It approximates the user experience.  View in Browser (CTRL+SHIFT+W). This option runs a selected page in the browser. Debugging breakpoints are not in effect even if debugging is enabled. Browser Options By default, Visual Studio uses your default browser to test pages. To use a different browser or Page Inspector, right-click the page in Solution Explorer and then click either Browse With or View in Page Inspector. The Browse Withlets you select a browser from a list, add new browsers to the list, or set one as the default browser. (The default browser setting here applies only to the Visual Studio environment and not to Windows.) Build Options By default, Visual Studio builds the web project when you run a page. Building the project helps you find compile-time errors before the page is displayed in the browser. You can set options to specify whether you want to build the entire project, the current page, or not build at all. For more information, see Building (Compiling) Web Site Projects. Running with a Startup Page By default, when you run a web project, Visual Studio runs the page that is currently open. However, in some cases you might always want to start your web project with a specific page. For example, your web project might have a home page where users make a selection that is required for other pages in the site or application. In this case, you can configure your web project to display that page first when you test run your application. To specify a start page, right-click the page in Solution Explorer and then click Set As Start Page. Note Setting a start page in Visual Studio affects only your testing. It does not set the start page for the website when it is published. To specify a default page for your website, first use Internet Information Services (IIS) Manager to enable a default document for your website or virtual directory. Then, select the page that you want. For more information, see the topic Configuring Default Documents in IIS 7. Running on a Specific Web Server When you run a page, Visual Studio launches the web server, launches the browser, and loads the specified page into the browser. In effect, Visual Studio passes the URL of the current page to the web server, and the web server runs the page that was requested. The web server that is used to run the page depends on the type of website you are working with:  For File system web projects, Visual Studio launches its own web server and runs the page locally. However, you can also specify a start URL to use when testing a web page. This method is useful if you want to test a file system website on another computer with IIS. For more information about the ASP.NET Development Server, see Web Servers in Visual Studio for ASP.NET Web Projects.
  • 100.  For local IIS Express, local IIS, and remote IIS sites, Visual Studio runs the page in the corresponding instance of IIS or IIS Express. For more information, see Web Servers in Visual Studio for ASP.NET Web Projects.  For FTP-deployed websites, Visual Studio runs the page by using the start URL that you provide as part of the FTP website properties. If you have not provided one, Visual Studio prompts you for the start URL when it is required. For more information, see FTP-Deployed Web Site Projects. For a remote website or FTP site, the remote computer must be running the same .NET Framework version that you are developing for. Running with the Debugger Running your page with the debugger enables you to perform debugging tasks, such as stepping through code and stopping at breakpoints. For more information, see ASP.NET Debugging Overview. Running with the debugger requires the following:  Configure the page or web project to enable debugging. This option compiles the page with extra information (debugging symbols) that the debugger uses. Visual Studio checks to see if debugging is enabled. If it is not, Visual Studio sets the compilation options in the local Web.config file to include debugging, creating the Web.config file if necessary.  Configure the web server with adequate permissions to allow the current user account to debug. If you are debugging a page that is running under IIS, you must be an administrator on the computer. If that is not practical, you can use IIS Express or the ASP.NET Development Server to debug applications without special permissions. For details, see Web Servers in Visual Studio for ASP.NET Web Projects and How to: Specify the Web Server for Web Projects in Visual Studio. Note Configure your pages or website to run without debugging before you deploy the site to a production server. Debugging options add overhead to the page and can affect server performance. Testing a Page You can test pages when you are developing web application projects or website projects in Visual Studio. To test run a web page  Perform one of the actions listed in the following table. All of the actions run the specified page in the default browser. To Do this Run the current page or startup page in the debugger. For information about the startup page, see the section How to: Specify a Startup Page for a Web On the Debug menu, click Start Debugging, or press F5. If the page or the website has not previously been configured to enable debugging, Visual Studio prompts you to enable debugging. If you choose not to enable debugging, the page runs in the default browser but does not allow you to attach a debugger to it.
  • 101. Site. Note Before you publish a website, disable debugging. Debugging adds overhead to performance and could display information to the user that you do not want to reveal. For details, see How to: Enable Debugging for ASP.NET Applications Run the current page or startup page without the debugger. For information about the startup page, see the section How to: Specify a Startup Page for a Web Site. On the Debug menu, click Start Without Debugging, or press CTRL+F5. Run the current page in a browser instance inside of Visual Studio. Right-click a blank area of the page and then click View in Browser. Note The View in Browser command is not available for files that do not render in a browser (such as the Web.config file). Testing with an Alternate Browser When you run a page, Visual Studio invokes the default browser. You can also test a page by using an alternate browser, as described in the following procedure. To test a web page with an alternate browser 1. In Solution Explorer, right-click the page you that want to test and then click Browse With. 2. In the Browse With dialog box, select an alternate browser. 3. If the browser that you want to use is not listed, click Add, specify the alternate browser program, and then click OK. Note
  • 102. You can set the alternate browser as the default browser for Visual Studio by clicking Set as Default. This option sets the default browser only for testing web pages in the current website. It does not affect the default browser setting in Windows. 4. When you have selected a browser, click Browse. Setting Build Options for Testing a Page Visual Studio can build the current page or the entire website when you run a page. Building helps you find compile-time errors before the page appears in the browser. You can set options to specify whether you want to build the entire site, the current page, or not build at all. To specify build behavior when running a page in a website project 1. In Solution Explorer, right-click the name of the website that you want to run, and then click Property Pages. 2. Click the Build tab. 3. In the Before running the startup page list, select the build option that you want before running pages. If you have configured the website to build before running a page, you can further specify what happens if the page or website has errors. To specify run behavior if build errors occur in a website or Web application project 1. On the Tools menu, click Options. 2. Select the Show all settings check box if it is not already selected. 3. Expand the Projects and Solutions node, and then click Build and Run. 4. Under On Run, when build or deployment errors occur, select the option for behavior that you want if the build process encounters an error. How to: Specify Start Pages for Testing Web Sites in Visual Studio When you use Start Debugging or Start Without Debugging to run a web project, Visual Studio runs the page that currently has the focus. However, you can set a start page to have your website or Web application always begin with the same page. If you set a start page, the Start Debugging or Start Without Debugging commands always run the page that you set, not the current page. Setting a start page in Visual Studio affects only your testing. It does not set the start page for the web project when it is published. To specify a default start page for a website, use Internet Information Services (IIS) to enable a default document and specify the page. For more information, see Configuring Default Documents in IIS 7. Note If you are working with a website for ASP.NET Web Pages (.cshtml files), use the procedure for website projects. To specify a start page for testing a web application project in Visual Studio 1. In Solution Explorer, under the Web application name, double-click the Properties folder.
  • 103. -or- In Solution Explorer, right click the Web application name, and then from the shortcut menu, chooseProperties. 2. On the Web tab, in the Start Action section, choose Specific Page. 3. Type the name of the file of the start page. -or-  In Solution Explorer, right-click the page that you want to specify as the start page, and then click Set As Start Page. To specify a start page for testing a website project in Visual Studio 1. In Solution Explorer, right-click the name of the website for which you want to specify the start page, and then click Property Pages. 2. In the Start Options tab, select the Specific page check box and then type or browse to the name of the start page. -or-  In Solution Explorer, right-click the page that you want to specify as the start page, and then click Set As Start Page . Walkthrough: Creating a Web Site with Membership and User Login Other Versions A typical requirement for Web sites is to allow only some users (authenticated users) to see certain pages. In that case, it is typical for the Web site to provide a way for users to log in and be authenticated, and to hide information from anonymous users (users who are not logged in). Note If you create a web application in Visual Studio using a Web project template, the template includes pages that implement basic login functionality using login controls and ASP.NET membership. However, the template does not include all the functionality that is described in this walkthrough. If the template does not include the functionality you want, or if you prefer to create the membership system yourself, you can use the same ASP.NET controls that are in the template to create custom login and membership pages.
  • 104. This walkthrough shows you how to manually put together these ASP.NET controls and ASP.NET membership services to create an application that authenticates users and that hides information from anonymous users. For information about how to use the Web site project templates, see Walkthrough: Creating an ASP.NET Web Site with Basic User Login. Tasks illustrated in this walkthrough include the following:  Creating a Web site.  Creating a home page that is accessible to all users.  Creating a login page.  Creating a members-only page.  Configuring membership.  Adding new users (members).  Letting users change their password.  Letting users reset a forgotten password. Prerequisites In order to complete this walkthrough, you will need the following:  Visual Studio or Visual Web Developer Express installed on your computer.  SQL Server Express installed locally on your computer.  Access to an email server that can forward email messages. (The server does not have to be able to receive messages.) If you do not have access to an email server, you can run the procedures in this walkthrough, but you will not be able to use the password-recovery feature. Creating the Web Site To create custom user login pages, you will first create an empty Web site. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a Web site 1. Start Visual Studio or Visual Web Developer Express. 2. On the File menu, click New Web Site. (If you do not see this option, click New, and then click Web Site.) The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Empty Web Site. You are selecting an Empty Web Site template because you will add membership and login capability by hand rather than using the features built into the other templates. 4. In the Web location list box, select File System and enter the name of the folder where you want to keep the pages of the Web site. For example, enter the folder name C:WebsitesMembership and then click OK. Visual Studio creates an empty Web site that contains only a Web.config file. Creating the Home Page You will first create the home page where all users of the Web site will start. To create a home page 1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item. The Add New Item dialog box is displayed.
  • 105. 2. If you do not see the Solution Explorer window, select the View menu and then click Solution Explorer. 3. Select Web Form, accept the default name (Default.aspx), and then click Add. 4. Switch to Design view and add text such as My Home Page. 5. In the Formatting toolbar, use the Block Format drop-down list to format the text as Heading 1. Creating the Login Page As part of your Web site, you must establish the user's identity (authenticate the user) so that the Web site can perform actions based on who the user is, such as showing or hiding information. To get the user's identity, you must have the user log in. Therefore, your Web site must include a login page. To create a login page 1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item. 2. Select Web Form, change the default name to Login.aspx, and then click Add. Note For this walkthrough, the page must be named Login.aspx. By default, ASP.NET authentication is configured to work with a page that has this name. (Although you will not do so in this walkthrough, you can change the default login page in the Web.config file.) 3. In the Login.aspx page, switch to Design view. 4. Add text such as Login Page to the page and again use Block Format to format the title as Heading 1. 5. Press ENTER to create a new paragraph. 6. From the Login group of the Toolbox, drag a Login control to the new paragraph. The Login control is a single control that will prompt the user for credentials and validate them. If you want, you can use the Auto Format link on the smart tag panel to apply formatting to the Login control. Displaying Detailed Login Errors The Login control includes validation to help users enter correct information. For example, if a user skips the password, a validator control displays an asterisk (*) next to the Password text box. To provide more detail about errors in the page, you will add a ValidationSummary control. To display detailed login errors 1. From the Validation group of the Toolbox, drag a ValidationSummary control onto the Login.aspx page. Drop the ValidationSummary under the Login control. 2. In the Properties window for the ValidationSummary control, set the ValidationGroup property to Login1, which is the ID of the Login control that you added previously. (If you do not see the Properties window, from the View Menu, click Properties Window.) 3. Save the page and close it. You can now test the login page. To test the login page 1. In Solution Explorer, right-click the Login.aspx page and select View in Browser. 2. Without entering anything into the login control, click Log In.
  • 106. An asterisk is displayed next to the User Name box and next to the Password box, because you did not enter values for these values. In addition, the ValidationSummary control displays error messages that provide details about the errors on the page. 3. Close the browser. Displaying Information for Logged-In Users The next step is to modify the home page to customize the display depending on whether the user is logged in. Anonymous users will see a generic message that invites them to log in. Logged-in users will see a message that welcomes them by their user name. To customize the display for logged-in users 1. Switch to or open the Default.aspx page and switch to Design view. 2. From the Login group of the Toolbox, drag a LoginView control onto the page. The LoginView control is displayed with its AnonymousTemplate template open. This template allows you to define the content that users will see before they log in. 3. Click the edit area of the LoginView control to activate editing. 4. In the edit area of the LoginView control's AnonymousTemplate template, enter You are not logged in. Click the Login link to sign in.. The following illustration shows the LoginView control edit area that contains the text. It might be easier to copy the text and paste it into the edit area or add the text as markup in Source view than entering the text directly into the edit area. The following example shows how the text appears in markup. <asp:LoginView ID="LoginView1" runat="server" > <AnonymousTemplate> You are not logged in. Click the Login link to sign in. </AnonymousTemplate> </asp:LoginView> 5. In Design view, select the LoginView control, and then on the LoginView Tasks panel, in the Views list, clickLoggedInTemplate. If you do not see the LoginView Tasks panel, right-click the heading of the LoginViewcontrol and then click Show Smart Tag. The LoggedInTemplate defines the content that will be displayed to users who have logged in. 6. Click the edit area of the LoginView control to activate editing and then enter the following text: You are logged in. Welcome, 7. Place the cursor in the edit area of the LoggedInTemplate after the text you just added. From the Login group of the Toolbox, double-click the LoginName control. The LoginName control displays the name of the user who is logged in. 8. From the Login group of the Toolbox, drag a LoginStatus control into the page. The LoginStatus control displays a Login link when the user is not logged in. When the user is logged in, the control displays a Logout hyperlink.
  • 107. 9. Save the page. Creating the Members-Only Page A typical task in many Web sites is to allow only logged-in users to view certain pages. Therefore, the next task for this walkthrough is to create a folder for members-only pages, add a page to it, and then create a rule that limits access to pages in the folder. To add a new folder to the Web site 1. In Solution Explorer, right-click the name of the Web site and then click New Folder. 2. Name the folder MemberPages. 3. In Solution Explorer, right-click the MemberPages folder and then click Add New Item. 4. Add a new Web Forms page named Members.aspx. 5. Click Add. Note Make sure that you create the page in the MemberPages folder. 6. Switch to Design view and add text to the page, such as Welcome to the members-only page. The exact text is not important, as long as you will be able to recognize this page when you see it in the browser. Use theBlock Format drop-down list to format the text as Heading 1. You can now add a hyperlink to the home page that sends users to the members-only page. In a real application, you would probably put the members-only page link in the logged-in template of the LoginView control. That way, visitors to your site would not see the link until they are logged in. However, for this walkthrough, you will make the link available to all users so that you can see the effect of trying to view a members-only page without first logging in. To link to the members-only page 1. Open or switch to open the Default.aspx page. 2. From the Standard group of the Toolbox, drag a HyperLink control onto the page. 3. In the Properties window for the HyperLink control, do the following: a. Set the Text property to Members-only page. b. Set the NavigateUrl property to ~/MemberPages/Members.aspx. This points to the page that you created previously. 4. Save the page. You can now test the hyperlink you just added to the home page. To test the link 1. In Solution Explorer, right-click the Default.aspx page and then click View in Browser. 2. Click Members-only page. The members-only page is displayed, because it is not protected yet. (Moreover, by default, ASP.NET uses Windows authentication, so it considers you logged in under your Windows credentials.) 3. Close the browser. Configuring Membership The next step is to configure ASP.NET membership and set up users. To do this, you can use the Web Site Administration Tool, which provides a wizard-like interface for making configuration settings. When you
  • 108. complete the configuration, a SQL Server database named ASPNETDB.MDF is created in the App_Data folder of the project. The database contains membership information for this Web site. For this walkthrough, you will define a single user. To create a membership user 1. On the Website menu, click ASP.NET Configuration. 2. Select the Security tab, click the Use the security Setup Wizard to configure security step by step link, and then click Next. The wizard displays a page where you can select the authentication method that your Web site will use. 3. Select the From the Internet option. This option specifies that your Web site will use ASP.NET forms authentication, which relies on the ASP.NET membership system. When you use forms authentication, users log in to the Web site by using the login page that you created earlier in this walkthrough. (The From a local area network option configures the Web site to use Windows authentication, which is practical if your site is accessed only by people who are on a corporate network. As noted earlier, this is the default setting for ASP.NET membership.) 4. Click Next. The wizard indicates that the application is configured to use advanced provider settings. By default, membership information is stored in a Microsoft SQL Server database file in the App_Data folder of your Web site. 5. Click Next. 6. Clear the Enable roles for this Web site check box, and then click Next. The wizard displays a page where you can create new users. 7. Enter information that defines a user of your Web site. Use the following values as guidelines. (You can use any values that you want, but be sure to note your entries. You will use these entries later in the walkthrough.) o User Name Your name (without spaces), or a sample name. o Password A password. A strong password is required (one that includes uppercase and lowercase letters, punctuation, and that is at least eight characters long). o E-mail Your personal email address. If you have to reset your password, this email address will be used to send you a new password. Therefore, you need to enter a valid email address. o Security Question and Security Answer Enter a question and answer that can be used later if you need to reset your password. 8. Select the Active User check box. 9. Click Create User. The wizard displays a confirmation page. Note Leave the Web Site Administration tool open. Setting Up Access Rules for the Members Page
  • 109. Earlier in the walkthrough, you created a folder named MemberPages and added a members-only page. In this part of the walkthrough, you will create a rule that makes sure that only logged-in users can access pages in that folder. To set up access rules 1. In the security wizard in the Web Site Administration Tool, click Next. The wizard displays the Add New Access Rules page. 2. In the Add New Access Rule box, expand the node for your Web site. 3. Select MemberPages, the folder that you created earlier. 4. Under Rule applies to, select Anonymous Users. 5. Under Permission, select Deny. The rule you are creating denies access to anonymous users — that is, users who have not logged in. 6. Click Add This Rule. The new rule is displayed in the grid. When users request a page from the MemberPages folder, the rules are checked to determine whether the user is allowed access to the page. 7. Click Finish. You are now done with the wizard. The wizard closes and you are returned to the Security tab of the Web Site Administration Tool. Testing the Members-Only Page You can test the members-only page by accessing it as an anonymous user or as a logged-in user. To test the members-only page 1. In Visual Studio, switch to the Default.aspx page and press CTRL+F5 to run the Web site. 2. When the Default.aspx page is displayed in the browser, do not log in. Instead, click the Members-only page link. The Login.aspx page is displayed, because access to the member’s page is denied for anonymous users. 3. On the login page, enter the user name and password that you used earlier to create the user to log in. When you log in, the site redirects you to the members-only page, because you are no longer an anonymous user. 4. Close the browser window. Adding New Users Earlier in the walkthrough, you created a user by using the Web Site Administration Tool. The Web Site Administration Tool is useful if you are working with a small, defined list of users, such as creating users for a small team. However, in many Web sites, users can register themselves. To support this feature, ASP.NET includes theCreateUserWizard control that performs the same task you performed earlier by using the Web Site Administration Tool. Creating a Registration Page In this part of the walkthrough, you will add a functionality that allows users to register on your Web site. You will start by creating a registration page. To create a registration page 1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item. 2. Add a new Web Form named Register.aspx and click Add.
  • 110. Note Make sure that you create the page in the root of the Web site, not in the MemberPages folder. 3. In the Register.aspx page, switch to Design view and enter text such as Register into the page. In theFormatting toolbar, use the Block Format drop-down list to format the text as Heading 1. 4. From the Login group of the Toolbox, drag a CreateUserWizard control onto the page. 5. In the Properties window for the CreateUserWizard control, set the ContinueDestinationPageUrl property to~/Default.aspx. This configures the control so that when users click Continue after they create a user, they are returned to the home page. 6. From the Standard group of the Toolbox, drag a HyperLink control onto the page. 7. In the Properties window for the HyperLink control, do the following: o Set the Text property to Home. o Set the NavigateUrl property to ~/Default.aspx. 8. Save and close the page. You will now add a link that displays the registration page to both the home page and the Login page. For this walkthrough, assume that you want to display the registration link only to users who are not logged in. To create a registration link on the home page 1. Switch to or open the Default.aspx page. 2. Right-click the LoginView control that you added previously, and then click Show Smart Tag. 3. In the LoginView Tasks panel, select AnonymousTemplate from the Views list in order to activate editing in the anonymous template. 4. From the Standard group of the Toolbox, drag a HyperLink control into the anonymous template. It might be easier to put the cursor in the editing area and double-click the HyperLink control in the Toolbox. 5. In the Properties window for the HyperLink control, do the following: a. Set the Text property to Register. b. Set the NavigateUrl property to Register.aspx. 6. Switch to or open the Login.aspx page. 7. From the Standard group of the Toolbox, drag a HyperLinkcontrol into the page. 8. In the Properties window for the HyperLinkcontrol, do the following: a. Set the Text property to Register. b. Set the NavigateUrl property to Register.aspx. You can now test the registration process. To test registration 1. Switch to the Default.aspx page and press CTRL+F5 to run the Web site and display the Default.aspx page. Because you are not logged in, the Register link is displayed. 2. Click the Register link. The registration page is displayed. 3. In the boxes, enter a new user name, a strong password, an email address, and a security question and answer. (All the pieces of information are required.)
  • 111. 4. Click Create User. A confirmation message is displayed. 5. Click Continue. You are returned to the home page as a logged-in user. Note that the Login link has changed to Logoutand that the information displayed in the Login control is from the LoggedInTemplate property, not from the AnonymousTemplate property. 6. Click the Logout link.The page changes to display the information for anonymous users. 7. Click the Login link. 8. Enter the credentials for the user you just created.You are logged in as the new user. 9. Close the browser window. Letting Users Change Their Password Users sometimes want to change their passwords, and it is often impractical to perform this task by hand. You can use another ASP.NET control to let users change passwords on their own. To change a password, users must know their existing password. You will add a page where logged-in users can change their password. To create a password-change page 1. In Solution Explorer, right-click the MemberPages folder, click Add New Item, add a new Web Form, name itChangePassword.aspx and then click Add. Make sure that you create the page in the MemberPages folder. You are putting the page in the MemberPages folder because only logged-in users can change their passwords. 2. In the ChangePassword.aspx page, switch to Design view and enter text such as Change Password and format it using Heading 1. 3. From the Login group of the Toolbox, drag a ChangePassword control onto the page. 4. In the Properties window for the ChangePassword control, set the ContinueDestinationPageUrl property to~/Default.aspx. This configures the control so that when users click Continue after they change a password, they are redirected to the home page. 5. Save and close the page. Creating a Password-Change Link on the Home Page You can now add a link to the home page that displays the ChangePassword.aspx page. You will make the link available only to users who are logged in. To create a password-change link on the home page 1. Switch to or open the Default.aspx page. 2. Right-click the LoginView control and then click Show Smart Tag. 3. In the LoginView Tasks pane, in the Views list, click LoggedInTemplate. This switches the LoginView control to edit mode for the content that will be displayed to users who are logged in. 4. From the Standard group of the Toolbox, drag a HyperLink control into the editing region. 5. In the Properties window for the HyperLink control, do the following: a. Set the Text property to Change password. b. Set the NavigateUrl property to ~/MemberPages/ChangePassword.aspx. Testing the Password-Change Page You can now test the password-change process. To test the password-change page 1. Press CTRL+F5 to run the Web site. 2. In the Default.aspx, page, click the Login link and log in as one of the users you have created. When you are finished, you are returned to the home page as a logged-in user.
  • 112. 3. Click the Change password link. 4. In the password-change page, enter the old password and a new password, and then click Change Password. 5. Click Continue. 6. On the home page, click Logout. 7. Click Login. 8. Log in with the new password. 9. Close the browser. Letting Users Reset Their Password When users forget their password, the Web site can enable them to recover or reset their password. The password can be recovered (that is, sent to the user) if the password is not hashed. When a password is hashed, the membership system does not store the actual password. Instead, the system processes the password using a one-way algorithm (a hashing algorithm) that produces a unique value for the password, and then stores this hash value. This algorithm can be repeated to test a user's password at login, but cannot be reversed to produce the actual password. This increases the security of the membership database, because getting access to the database does not mean that passwords are exposed. By default, the membership provider stores the password as a hash value. Therefore, the password cannot be recovered. Instead, if a user has forgotten a password, the Web site must generate a new password and send it to the user in email. For your Web site to send email messages your computer must have access to a Simple Mail Transport Protocol (SMTP) server. In this procedure, you will add a password-reset page to your Web site and configure the Web site to send users a new password by email. To reset a password, a user must provide a user name and must answer the security question that was provided when the user registered. The new password is sent to the email address that the user provided when registering. To create the password-reset page 1. In Solution Explorer, right-click the name of the Web site project and then click Add New Item. 2. Add a new Web Form page, name it PasswordRecovery.aspx and click Add. Note Make sure that you create the page in the root of the Web site, not in the MemberPages folder. 3. In the PasswordRecovery.aspx page, switch to Design view and enter text such as Forgot Password into the page and format it as Heading 1. 4. From the Login group of the Toolbox, drag a PasswordRecovery control onto the page. 5. Open or switch to the Login.aspx page and switch to Design view. 6. From the Standard group of the Toolbox, drag a HyperLink control onto the page. 7. Set the Text property to Forgot password and the NavigateUrl property to ~/PasswordRecovery.aspx. Configuring the Web site to Use an SMTP Server Next, you will configure your Web site to use an SMTP server. To configure the server correctly, you must have the setup information. If the server requires authentication, you will need the user name and
  • 113. password. For information about how to obtain this setup information, contact the system administrator. After you have determined how to access the SMTP server, you must configure your Web site to route email messages to that server. You can do so in the Web Site Administration Tool or by making an entry in your Web site's Web.config file, which contains a series of settings that determine how your application runs. The following procedure shows how to use the ASP.NET Web Site Administration Tool to perform this task. To configure the Web site to use an SMTP server 1. On the Website menu, click ASP.NET Configuration. 2. In the Web Site Administration Tool, click the Application tab. 3. Under SMTP Settings, click Configure SMTP email settings. The tool displays a page where you can configure email. 4. Enter the information that the page prompts you for. 5. Click Save, and in the confirmation page, click OK. The Web Site Administration Tool creates a Web.config file that has the settings that you have made in themailSettings section. 6. Close the browser window in which the Web Site Administration tool is displayed. 7. Open the Web.config file. 8. Under the system.net element and under the mailSettings element, verify your smtp and host settings. Note If your SMTP server requires a secure connection, you must set the enableSsl attribute to true. You do this in the network section of the smtp element in the Web.config file. 9. The SMTP settings in the Web.config file will resemble the following example. 10. <system.net> 11. <mailSettings> 12. <smtp from="[email protected]"> 13. <network host="<server>" password="<password>" 14. userName="[email protected]" enableSsl="true" /> 15. </smtp> 16. </mailSettings> 17. </system.net> Security Note To protect configuration information like the user name and password, you can have ASP.NET encrypt the portion of the Web.config file where the SMTP information is stored. For more information, seeEncrypting Configuration Information Using Protected Configuration. In addition, by default ASP.NET sends the smtp server credentials in clear text and can be intercepted by programs that record network activity. For a
  • 114. production site, you should use the SSL (secure sockets layer) to encrypt sensitive information that is exchanged with the server. Testing Password Reset You can now test the process of resetting your password. You will then use the new password to log in. To test the password-reset page 1. Press CTRL+F5 to run the Web site. 2. Click Login. 3. In the Login page, click the Forgot password link. Enter your user name and then click Submit. 4. Enter the answer to the security question and then click Submit. 5. Wait for a few minutes and then check your email. 6. Use the new password to log in.