Sie sind auf Seite 1von 32

An Introduction to Developing Web Sites in ASP.NET 2.

0
Hands-on Lab Manual (Day 1)

Exercise 1: Creating Web Sites with ASP.NET


In this exercise we are going to create a very simple web site which gets blog entries from a database and shows them on a web page.

At the end of this exercise you will be able to: Create a web site using Visual Web Developer 2005 Use the DataList control to show repeating data from a database.

ASP.NET Overview When Microsoft released the first version of .NET in 2002, they also unveiled their new web platform, ASP.NET. This was not a simple evolution of ASP but a radically new paradigm for web development, finally allowing web developers to create web applications in a similar way to the way in which desktop applications had been developed for years, complete with object orientation and a powerful event model. Using Visual Web Developer with ASP.NET means that you can drag intelligent controls on to your canvas, which can adapt to different internet browsers. You can attach events to them in the same way as a Windows application, and call upon the full resources of the .NET framework to talk to databases, consume and publish web services, process XML, talk to back-end systems almost anything you could do in a traditional Windows application, you can now do with ease on the Internet too. With Visual Studio 2005, Microsoft sees this technology enter a second generation, and now it is easier than ever to develop professional looking and acting web sites with a minimum of code. In fact, as we will see in the next exercise, you can write a data driven web site without writing a single line of code.

Task 1 Creating a Simple ASP.NET Application In this task we are going to create a very simple web site which we will then build upon in later tasks and exercises to create our blog. To open Visual Web Developer Express, navigate to your Start menu and select Programs | Visual Web Developer 2005. Select the File menu and then select New Web Site

Figure 1 | New Web Site Dialogue

Type a name and location for your project e.g. C:\Documents and Settings\LabUser\My Documents\SimpleBlog, then click OK to create your project.

Figure 2 | Source View

Note: One of the things you may notice straight away is that ASP.NET 2.0 uses standards-compliant XHTML 1.1 by default for all pages.

The first thing we need to do with our new web site is add a database. A database has already been created with some pre-populated blog entries, which we will now add to the project. Right click the web site in the solution explorer at the top right hand side of Visual Web Developer and select Add | Existing Item...

In the dialog that appears, find the Database.mdf file in the My Documents folder and select it.

Click the Add button to add the database to your project. Visual Web Developer will automatically add your database to the App_Data folder. Now we have a database from which to get data, lets get some data from it. First, switch to the design view by clicking the Design tab at the bottom left of the designer window: 4

Now, in the toolbox on the left hand side of Visual Web Developer, expand the Data tab, and double click DataList to add a data list to the default.aspx page.

You can see a small box containing an arrow at the top, right hand side of the newly created DataList, this SmartTag allows you to quickly configure an ASP.NET control. Visual Web developer will automatically activate the SmartTag for a control when it is added to a web page. In the above screen shot, the DataList Tasks window was shown when the DataList was added to the page.

In DataList Tasks, select the Choose Data Source drop down list, and choose <New data source...> which will open the data source configuration wizard:

Choose Database and give a meaningful ID for the data source, e.g. BlogDataSource, then click OK

In the drop-down list, select the database we added earlier Database.mdf, and then select Next.

Give the connection information a meaningful name, for example, BlogConnectionString, and then select Next.

Now the DataList knows which database we want to connect to, we can now tell it what information we want. Start by choosing tblPosts from the Name: drop down list, and then ensure PostTitle, PostBody, PostAuthor, and PostData are checked. Select Next to move to the next step. 7

We are now ready to test the data we are retrieving, select Test Query and the data source configuration wizard will return the configured data from the database. If everything is okay, we can now select finish to finalise our changes and close the wizard.

We are now ready to test the web site, select the Debug menu and then choose Start Debugging. Visual Web Developer will then prompt you to enable debugging:

After you select OK to continue, Visual Web Developer will enable debugging for the web site, and launch a web browser showing our web page:

There you have it, youve written your first data driven web site. It isnt very pretty yet, however, there are a few cool things going on: Cool Thing #1: If you have a look at the address bar in Internet Explorer you will notice a really odd port number, this is because, Visual Web Developer, and its much bigger brother Visual Studio, both ship with a special development web server which means you dont need to install one yourself. This makes developing and debugging web sites much easier than it has ever been before. Cool Thing #2: Weve not written a single line of code. You can get by in ASP.NET with writing very little or even no code for a lot of tasks that previously would have taken dozens or even hundreds.

10

Task 2 Master Pages In this task we are going to look at a very powerful feature in ASP.NET 2.0, namely, Master Pages. Master Pages are designed to solve one of the recurring difficulties in web development how to ensure consistent layout and style across pages in a maintainable way. This task will show you how Master Pages approach and solve this problem. To add a new master page, right click the web site in the solution explorer at the top right hand side of Visual Web Developer and select Add | New Item...

The following dialog appears:

Choose Master Page and then click the Add button:

11

As you can see, a master page mostly consists of ordinary XHTML markup, but there is also an additional tag:
<asp:ContentPlaceHolder ID="IndexContent" runat="server" />

A master page can have any number of content place holders, which, as their name suggestions, are place-holders which get replaced with content by pages which use that master page. This process will become clear in the remainder of this task. The first thing we are going to do is change the title tag to something more appropriate as a default, for example, Simple Blog:
<head runat="server"> <title>Simple Blog</title> </head>

Next, change the master page body so that we can use a cascading style sheet to theme our blog by replacing:
<form id="form1" runat="server"> <div> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> </div> </form>

With:
<form id="form1" runat="server"> <div id="Container"> <div id="Header"> </div> <div id="Index"> <asp:ContentPlaceHolder ID="IndexContent" runat="server" /> </div> <div id="Body"> <asp:ContentPlaceHolder ID="BodyContent" runat="server" /> </div> <div id="Footer"> </div> </div> </form>

Next, add Winter.css, Header.gif, and Footer.gif to your project from the Day 1 Files\Winter directory.

12

13

Now we can refer to the Winter.css style sheet from the master page, to do so, add the following tag to the head element:
<link rel="stylesheet" type="text/css" href="Winter.css" />

As you type, Visual Web Developer provides a feature called Intellisense. For example, when you type href=", Visual Web Developer will show you a drop down list of files you can use as a style sheet. Thats all we need to do to configure the master page, now it is time to change the page we created in the first task to use it. Switch back to the source code view for Default.aspx, you can do this by double clicking Default.aspx in the Solution Explorer and then select Design at the bottom left of the window. First we need to tell the page file about the master page, to do this we need to change this line:
<%@ Page Language="CS" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

To this:
<%@ Page Language="CS" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" MasterPageFile="~/MasterPage.master" %>

Notice again, as you type MasterPageFile="~/, Visual Web Developer provides a list of possible master pages.

Once you have changed this, you will probably notice red wavy underlining appear under most of the code in the page. This is because the master page provides the html, head, body, and some of the other elements for our page, so we need to change our page so that it only includes the content for that page, and so that it knows which content place holder to put the content in.

14

First, add a content section:


<asp:Content runat="server" ContentPlaceHolderID="BodyContent"> </asp:Content>

Now, move the markup for the DataList into the content section as shown below:

15

Now remove everything from <html> to </html> including the html tags themselves, when you are finished, the markup should look like the following screenshot:

If you run your web site now by clicking Debug | Start Debugging, your web site should appear something like:

Here, the screen shot shows the same site in both Internet Explorer 7 and FireFox 2.0, although the web site is only very simple at the 16

moment, this illustrates how Visual Web Developer generates standards compliant code that work across all of the major browsers.

17

Task 3 Adding a Comments Page In this task, we are going to add a second web page to the site that allows us to view the comments associated with the blog entries displayed on the main page. To add the new page to the project, right click the web site in the solution explorer at the top right hand side of Visual Web Developer. Select Add | New Item... In the dialog that appears, select Web Form and enter the name Comments.aspx. Before clicking Add, ensure that select master page is chosen.

It was necessary to change some of the mark-up to associate the master page we created with the Default.aspx page. However, if we choose to select a master page upon creating a new page, as we have done above, Visual Web Developer offers a convenient method to associate the two without having to edit any mark-up whatsoever. After clicking Add, the following dialog box will appear. Choose MasterPage.master and click OK. Visual Web Developer then creates the new page already associated with the master page.

18

When Visual Web Developer has finished creating the new page, click once within the content area of the page and add a data list just like you did in Task 1 (by double clicking the DataList control within the toolbox on the left hand side). Using the SmartTag on the data list control, we are now going to link the control to the comments table in the database. On the SmartTag, go to Choose Data Source |New Data Source

In the dialog that appears, choose Database as the data source type, and give the data source an ID of BlogCommentsDataSource. Then click OK.

19

Choose the BlogConnectionString connection you created before as the data connection and click Next.

Next, configure the Select statement that will be used by the data source to retrieve comments from the database. Choose to specify column from a table or view and select tblComments as that table. In the list of columns available, choose CommentTitle, CommentBody, CommentAuthor and CommentDate. There is no need to select either CommentId or PostId since these are used by the database to keep track of comments and the posts to which they belong.

20

If used as it currently is, the data source would return all comments from the database. Since were only interested in displaying the comments for a particular blog post, we can set up the data source to use a Where clause, which acts as a filter. To do this, click on Where; a new dialog box appears. Within the database, comments are associated with a particular blog entry through the foreign key PostId. This allows us to know which blog entry a particular comment refers to. But how can we discover which blog entry the user is viewing? If you have ever used a website with a ? in the URL, you have already experienced QueryStrings. These are used to pass small amounts of data across web pages. For instance, the following URL: http://localhost/SimpleBlog/Comments.aspx?PostId=13d9babf-d9f0-4f1fhttp://localhost/SimpleBlog/Comments.aspx?PostId=13d9babf-d9f0-4f1f8f9f8f9f-ac933c57fcd0 makes a blog post available to the comments page ID using the name PostId and having the value 13d9babf-d9f0-4f1f-8f9fac933c57fcd0. So, we now have a PostId available through the QueryString and a corresponding field in the database; all that remains is to connect the two. In the dialog box, choose PostId as the column, = as the operator, QueryString as the source and finally PostId as the QueryString field. There is no need to enter a default value.

21

After doing this (the result should look like the screenshot above), click Add to insert the condition to the Where clause, and then OK to finalise the Where clause. We need to change one piece of the mark-up generated by the wizard, switch to the source view on the page, you should see some mark-up that looks like:
<SelectParameters> <asp:QueryStringParameter Name="PostId" QueryStringField="PostId" Type="Object" /> </SelectParameters>

The PostId type is actually a string not an object, unfortunately this cant be changed in the wizard, but if you change the above mark-up to:
<SelectParameters> <asp:QueryStringParameter Name="PostId" QueryStringField="PostId" Type="String" /> </SelectParameters>

Everything will work fine. Switch to the default.aspx page so we can link the comments page in.

22

Click on the data list and choose Configure Data Source from the SmartTag.

Skip through the sections in the Wizard until you reach Configure the Select Statement. From there, simply select PostId in the columns list to add it to the list of columns returned from the database. When we first configured the data source we didnt need the PostId, however, we need it now to pass to the comments page so it can filter the comments for the desired post.

Then, continue clicking Next until you reach the end of the Wizard at which point click Finish to accept the changes.

23

Visual Web Developer will recognise that you have changed the data source and offer to replace the existing item template with one that includes the new PostId column you have added. As mentioned though, PostId is a field used by the database to keep track of posts there is no need to display it to the user. So, click No to keep the existing template.

Now you have created the comments page and edited the data source on the main page, blog posts in the data list will be aware of their PostIds and the comments page will be able to accept a PostId and show the comments for that post. Finally, we need to add a hyperlink to link to the comments page for each post. The best place to add this is in the item template in the data list; doing this will display a comments link underneath each post. Click on the data list and choose Edit Templates from the SmartTag.

After clicking on this, a new SmartTag will appear allowing you to choose the template to edit. Set this to ItemTemplate. The DataList control has other templates, e.g. AlternatingItemTemplate for items on even-numbered rows, SeparatorTemplate for content between items, and so on. These are beyond the scope of this lab, but take your time to investigate these if you have some time spare.

24

Click within the item template; this will turn the border blue and ensure that any controls you add are inserted into the template rather than directly onto the page. Click to the right of PostDate: [PostDateLabel] to move the cursor there and press enter to drop down to the next line. Double click on the Hyperlink control from the toolbox to add it. On the hyperlinks SmartTag, choose Edit DataBindings

The DataBindings dialog appears from which you can bind various properties of the hyperlink to the data source. Select NavigateUrl to set binding information for the URL the hyperlink represents.

25

We want to pass the post ID to the comments page, so select the PostId from the Bound To drop down list.

Binding the PostId on its own is not enough as we want the URL to be something like Comments.aspx?PostId=<PostId>, to do this, set the Format to Comments.aspx?PostId={0}. When the binding is evaluated, the {0} gets replaced with the value from the PostId field.

26

Complete the data binding by clicking OK. Use the property grid to set the Text property of the HyperLink to something like Show Comments..

27

Thats it! If you run the web site now, and click on the Show Comments.. link for one of the blog posts, you should see something like:

28

Task 4 Adding a New Blog Entry Box In this task, we are going to add a new page page which will allow new blog entries to be created. Add a new page to the web site, using the master page we created earlier. Select a FormView from the toolbox and add it to the page.

Select Choose Data Source.. | <New data source...> Give the data source a name, e.g. AddBlogPostDataSource, then select OK. Select the BlogConnectionString connection string you created earlier, then click Next. Select the tblPosts table, and then select PostTitle, PostBody, and PostAuthor. Click Next and then Finish to close the wizard.

We now need to tell the data source how to insert data into the blog, so, select the data source.

29

In the property grid, find the InsertQuery property, and open its editor by click the ellipsis button on the right hand side.

Set the INSERT command to be:


INSERT INTO tblPosts(PostTitle, PostBody, PostAuthor) VALUES (@PostTitle, @PostBody, @PostAuthor)

In the properties window, find the DefaultMode property and change its value to Insert. You probably want to return the user back to the blog page after inserting some data, to do that, we need to handle an event on the FormView. Select the FormView, then, switch to the event view in the property grid by clicking the lightning bolt icon.

30

Double click the ItemInserted event to create an event handler ready to write some code. Add the following code to your event handler:
Response.Redirect("default.aspx");

Thats everything! Run your web site and you will find you can now add a blog entry, and that when you have done so you will be taken back to the main blogs view.

31

Summary of Lab (Day 1)


This lab has introduced you to the basics of creating data driven web sites with ASP.NET 2.0, as well as some of the concepts that make designing and maintaining the visual part of a web site much easier. In the entire lab, weve only had to write a single line of code that redirects from one page to another, ASP.NET 2.0, when combined with an IDE such as Visual Web Developer which provides graphical wizards for configuring data sources, has an impressive range of features which facilitate a no or low-code approach to development.

Useful Resources: http://asp.net/ - The Official ASP.NET Web Site http://msdn.microsoft.com/ - The Microsoft Developer Network

32

Das könnte Ihnen auch gefallen