In this exercise you will create a new web site using a WebMatrix template, and then modify the outline style and appearance. You will also add a section to the home page that displays items of news about the club. Along the way, you will learn how to add tables to the database that WebMatrix includes in your application, and how you can use jQuery to animate the user interface.

WebMatrix is one of several tools that Microsoft provides for building websites. Other more complex and comprehensive environments such as Visual Studio and Visual Web Developer Express contain additional capabilities, such as visual designers and a wide range of controls that you can use in your pages to implement server-side and client-side features.

However, the simplified working environment of WebMatrix, combined with the powerful but compact coding paradigm it supports, enables newcomers to web development on the Microsoft platform to get started more quickly and easily. After you master web development using the features and techniques supported in WebMatrix, you will find it easy to move to other development tools.

By the end of this exercise, you will be familiar with the main features of WebMatrix and how you can use code in your web pages that runs on the server, and code that runs inside the browser (client-side code). You will also understand how you can modify the appearance and style of the default template.

You should be able to complete each of the tasks within 20-30 minutes.

Task 1 - Create the Default Site from a Template

In this task, you will create the default base website using a template provided with WebMatrix, and explore the environment it provides.

To create the base website from a template

Open the Start menu, click All Programs, expand the folder named Microsoft WebMatrix, and click Microsoft WebMatrix.

The initial screen provides four options for creating or opening a website. The My Sites option shows a list of sites you have already opened or created. The Site From Web Gallery option opens a list of online templates that you can download and use to create a new website. The Site From Template option shows a list of the templates installed on your computer. Finally, the Site From Folder option allows you to open an existing website on your computer.

Note:

WebMatrix includes several templates that you can use as a starting point for developing your own sites. For example, there are templates that create a fully working bakery website, a photo gallery, and a calendar application. As you become more experienced with website development, you can examine these to see how they implement different features and use the code they contain in your own applications. The Web Gallery option allows you to create sites based on templates submitted by third parties. There are around 40 templates (and growing) to choose from, so you should never find you are short of inspiration for developing your own distinctive sites.

Click the Site From Template option. This shows a list of templates installed locally on your computer. If you wanted to start with a completely empty site and add all of the pages yourself, you would select the Empty Site option. However, for this exercise you will begin with the Starter Site, which contains the main items required for most websites but is easy to adapt and extend as you wish. Click the Starter Site option, change the Site Name to SoccerWebsite (as shown in the following screenshot) and then click OK.

The main WebMatrix interface now appears. The lower left panel contains links to change between the four main views of the site. The default starting view is Site view, which contains information about the site (such as the URL and the physical path) and links and information to help you get started. The main left-hand panel contains links that allow you to view the requests made to the site, and the default settings for features such as the .NET code version and the types of pages that are opened by default when visitors access the site. Feel free to examine these options, but do not change any of them in the exercise project.

Click the Files option in the lower-left panel. The main left-hand panel now shows an expandable tree view of the files contained in the website. If you double-click on a file, it opens in the main window. You can also use the link in the main widow to add new files (such as web pages, style sheets, or many other types of resource) to the site. However, do not add any new resources yet. The default template provides all the files you require at the moment.

Expand the folders in the left-hand panel so that you can see all of the files. The files are organized as follows:

The Account subfolder contains the files that create the web pages visitors can access to register with the site, log into the site, and maintain their account (such as, for example, resetting or changing their password). Files with the cshtml file extension contain C# code that is executed on the server to create the HTML page that is sent to the browser.

The App_Data subfolder contains a database file named StarterSite.sdf. This file is loaded into the SQL Server Compact Edition database application (installed with WebMatrix) when you run the site. You will learn more about this database later in this exercise.

The Styles subfolder contains a Cascading Style Sheet (CSS) file named Site.css. This defines the style and appearance of the elements and text in the web pages. You will edit this file later in this exercise to change the appearance of your site from the default.

The remaining files under the site project folder serve a range of purposes. The _AppStart.cshtml file defines global variables that are available throughout the code in the site. The _SiteLayout.cshtml file defines the layout and appearance of other pages in the site to provide a consistent appearance. The Default.cshtml file is the default start page for the site, which visitors will see if they do not specify a page when they access the site. The About.cshtml file is the "About" page for the site. The favicon.ico file is the icon that the browser will display on tabs and in the address bar when visitors access pages within the site. The robots.txt file is used to tell search engines and web spiders which files and folders they can index when crawling your site.

Note:

Notice that two of the file names - files that are not actually pages that visitors can view - start with an underscore. WebMatrix will not serve (allow visitors to access) any files whose name starts with an underscore. They are classed as system files for the site.

Open the cshtml files and the style sheet to view the contents by double-clicking on these files in the left-hand navigation pane. Each one opens in a tab in the main window. Later in this exercise you will learn about what the contents of these files does, and how you can modify it. For now, however, do not change anything. Just close the files again using the small "x" icon in each tab.

Click on the file named Default.cshtml in the navigation pane, and then click the Run button on the Home tab of the toolbar ribbon at the top of the WebMatrix window.

Note:

Alternatively, if you have more than one web browser installed on your computer you can click the down-arrow below the button and select the browser in which to view the site, or even have WebMatrix display it in all of the installed browsers. This allows you to easily check that the site works correctly in different browsers.

By default, the site is displayed in Internet Explorer. The page you see is the Default.cshtml page. Click the About button in the page to see the About.cshtml page. You can, if you wish, experiment by registering and logging in to the site. However, we won't be exploring or using this feature until Exercise 4.

You have now completed this task, and you should have a broad understanding of how you use WebMatrix to create a base site from a template, and view the site in a browser. In the following tasks of this exercise you will modify the files in the site, and learn how the HTML and code they contain creates the output you see in the browser.

Task 2 - Modify the Appearance of the Site

In this task, you will modify the website you created from the default Starter Site template to show a more personalized appearance suitable for the soccer team site. This includes editing the contents of the site layout page, the main page, and the style sheet that defines the appearance of the page content.

Styling and Layout in Web Pages

In the past, web pages used elements embedded within the HTML to specify the layout and appearance of the page content. However, this mixing of data (the text displayed in the page) and presentation information (the colors, fonts, and positioning of the text content and images) makes it hard to modify pages and present a consistent look and feel across multiple pages.

Instead, the accepted technique is the use of Cascading Style Sheet (CSS) definitions to specify the layout and appearance of individual elements or element types. For example, you can define the font size, family, and color for all content within a paragraph (<p> element) or a hyperlink (<a> element) as a set of CSS style selectors and the browser will apply the resulting combination of styles to all elements of this type. In addition, you can specify styles for individual elements by specifying them using the element identifier, or the position within a hierarchy of elements (such as all of the <li> list item elements within an <ol> ordered list element).

You can apply styles directly within the HTML of each page, either in a <style> section in the <head> section of the page or by applying the class attribute to individual elements within the page content. However, this defeats the objective of making style changes at site level easy. Instead, you should consider creating a separate style sheet for the entire site as a .css file, and then apply it to every page using a <link> element in the <head> section of each page. This has the added advantages that the browser can download the style sheet once and then cache it to reduce loading times, and you can even specify more than one style sheet for pages so that the user can select the one to use (useful if you want to provide alternatives such as large text, or a black and white version for visitors who are colorblind).

Site Layout Pages in WebMatrix

In addition to using a separate style sheet to define the appearance of multiple pages in a website, you can provide a consistent look and feel using a site layout page (often referred to as a master page) that contains all of the content not specific to individual web pages. For example, you can define the site header and footer sections, the navigation links, and other types of content that appear on every page in a site layout page. Then each page of the site need only contain the content specific to that page.

The default Starter Site template you used in the previous task uses a site layout page named _SiteLayout.cshtml. Visitors do not request this page when they are navigating the site (remember that files whose name starts with an underscore cannot be accessed by visitors). However, each page that they do request, if it contains a link to the site layout page, is combined with the site layout page and the result is sent to the visitor's browser. The following schematic shows an overview of the process.

Notice how each page references the site layout page file, and how the site layout page uses the RenderBody method to insert the contents of the requested page. Other options for using site layout pages are the RenderPage and RenderSection methods. You will see the RenderPage method used in Exercise 2. For more information on these and on using the RenderBody method, see "Tutorial - Creating a Consistent Look" on the official ASP.NET site at http://www.asp.net/webmatrix/tutorials/3-creating-a-consistent-look.

The Steps for Modifying the Appearance of the Site

Now that you understand more about styles and site layout pages, it's time to get started modifying the default site you created in the previous task.

To modify the appearance of the default website

Continue with the SoccerWebsite site you created in the previous task. If you have closed WebMatrix, open the site. You can either:

Start WebMatrix, click the My Sites option in the opening screen, select the SoccerWebsite site in the list of recent sites, and click OK.

Navigate to your Documents\My Web Sites folder in Windows Explorer (in Windows 7, this is within the Libraries folder), right-click on the SoccerWebsite folder, and then click Open as a Web Site with Microsoft WebMatrix.

Click the Files option in the lower-left corner of the WebMatrix window to show a list of files in the site, and then click the small arrow next to the Styles folder to open it. You will see the CSS file named Site.css. Double-click this file to open it in the main editor window.

Note:

One of the main benefits of Cascading Style Sheets is that, as the name suggests, style definitions cascade from the page or parent element to all the child elements unless they are redefined further down this hierarchy. The default style sheet takes advantage of this property to, for example, set the base color for the site to blue. You can see this in the comment and in the definition of the style for the body element of the page near the start of the style sheet.

Edit the definition of the body style in the style sheet so that the site will have a green background instead of the default blue background, as shown in the following highlighted code.

If you decide to run the site to see the changes as you edit the style sheet, remember to select the page Default.cshtml in the left-hand tree view before you click the Run button in the toolbar ribbon. If you don't do this, you will see an error page in the browser because WebMatrix cannot find a default document in the Styles folder.

By default, the headings displayed in the pages are black text, but they will look better in a matching dark green color. Find the section of the style sheet that defines the heading styles, and edit the color that is used for all six standard heading text elements as shown in the following highlighted code.

The remaining place where you need to change the colors is for the navigation tabs that allow visitors to open the pages in the site. At the moment there is just a "Home" tab and an "About" tab, but later you will add more. These tabs are defined in the HTML in the _SiteLayout.cshtml file as an unordered list using a <ul> element with id="menu" and a series of nested <li> elements, one for each tab, as shown here.

The style definition for these elements is in the section of style sheet that follows the comment "/* Tab Menu". This section starts with a definition of the style for an element of type <ul> that has an attribute id="menu" using the style selector "ul#menu". Change the color of the bottom border for the menu from the default blue to the same color as the page background, as shown in the following highlighted code.

The menu style definitions continue by defining the style of nested <li> elements using the style selector "ul#menu li", and the style for hyperlinks (<a> elements) nested within each of the <li> elements using the style selector "ul#menu li a". Edit the last of these styles to change the color of the hyperlink text to dark green as shown in the following highlighted code.

Click the Save icon in the WebMatrix window title bar and then click the small "x" on the Site.css page tab in the main editor window to close the file. You are finished editing it.

Note:

Next, you will edit the site layout page for the site to replace the default site title "My ASP.NET Web Page" with an image showing the name of your new site, and modify other parts of the page. The images you will use are provided in the samples for this guidance.

In Windows Explorer, navigate to the folder \Examples\Exercise_01\Resources. Copy the file named favicon.ico into the root SoccerWebsite folder in your Documents\My Web Sites folder so that it replaces the existing file. Then copy the file named site-header-image.png into the Styles subfolder of your SoccerWebsite folder.

Back in WebMatrix click the Stop icon in the toolbar ribbon. Then right-click the top-level SoccerWebsite item in the left-hand tree view and click Refresh. You will see the two new files appear in the list of files (expand the Styles folder to see the site header image).

In the left-hand tree view, double-click the file _SiteLayout.cshtml to open it in the main editor window. This is the site layout page file for the site that defines the header and footer text, and the navigation tabs

Note:

At the top of the page you will see the <head> section. Notice that it contains two <link> elements. The first of these is the link to the CSS style sheet you modified earlier in this task. The second is the link to the "favorite" icon that the browser will display in the address bar when visitors navigate to the site.

Edit the <title> element in the <head> section as shown in the following highlighted code so that the title of the page (as displayed in the title bar of the browser) is "MySoccerTeam" and the name of the actual page. Remember that this site layout page will be used by all of the pages in the site.

The @ character you see in the elements above instructs the web server to execute the code that follows instead of just sending it to the browser. The code @Page.Title causes the web server to send the value of the Title property of the current page to the browser. You will find this value is set in the About.cshtml and Default.cshtml files. The @Href("...") code is a function that is executed by the web server. It uses the value passed to it in the brackets to create the appropriate URL for the href property of the <link> element. The ~ character at the start of the URL is translated into the path to the root of the site, which ensures that the browser will create the correct path even if the page containing the <link> element is in a subfolder of the site. If you only specify the path in the usual way (using, for example, href="Styles/Site.css") the path will be incorrect if the page is in a subfolder of the site and not in the root folder.

Now look at the start of the <body> section of the page. It contains the following <p> element that creates the text title within the body of the page, applying the CSS style definition named site-title to it to specify the appropriate size and format for the text.

However, you want to replace this with the image containing the name of the site that you copied into the Styles folder in a previous step. Delete the entire <p> element and replace it with an <img> element that specifies the image file to display, as shown in the following highlighted code.

Notice that the <img> element also uses the Href function to create the correct path to the image file. The alt attribute defines the text that will be displayed if the browser does not support images (such as special user agents for visually impaired users).

The final change to the site layout page file is to edit the footer text. Find the <div> element with the attribute id="main" near the end of the page. Within this is a <div> element with the attribute id="footer". Edit the content of this to display an appropriate copyright statement as shown in the following highlighted code.

You have now finished editing the site layout page. Click the Save icon in the WebMatrix window title bar and then click the small "x" on the _SiteLayout.cshtml page tab in the main editor window to close the file.

In the left-hand tree view, double-click the file named Default.cshtml to open it in the main editor window. At the moment, this page contains only the following code.

Notice that the code block at the top of the page (the section prefixed with the @ character and enclosed in curly braces) specifies that the site layout page is the file _SiteLayout.cshtml that you have just been editing. You can also see how the code sets the Title property of this page, which is then used in the <head> section of the maser page (as you saw earlier in this task).

With the file Default.cshtml selected in the tree view, click the Run button on the toolbar ribbon to open the page in your browser. You will see the changes you made in the page, including the new colors for the background and text, the new site header image and title, the updated footer text, and the new "favorite" icon in the browser address bar.

Note:

You may have to delete the contents of your browser cache and close it, then click the Run icon to see the new favorite icon.

You have now completed this task, and you should have a broad understanding of how you can use CSS and site layout pages in WebMatrix to specify the look and feel for a site and for the individual pages it contains. In the next task of this exercise you will start the process of adding some content to the default "Home" page of the site.

Task 3 - Add the News Items Database

Now that you have modified the appearance of the new website, you can start to create the pages it will contain. The Starter Site template you used to create the site contains two pages: a "Home" page named Default.cshtml and an "About" page named About.cshtml. In this task, you will modify the Home page to include a list of news items about the soccer club.

Creating Dynamic Content for a Website

There are several ways that you can generate content such as news items in a web page. You can hard-code the content as plain text and HTML elements, but this means that an administrator must edit the page each time a new item is added or the existing items are edited or deleted. Effectively, the administrator must replace the existing page on the site with a new version each time (which may be difficult when the site is hosted on a remote server) and does not allow multiple users to safely add or edit items.

Typically, for information such as news items and other data that changes regularly, you will use an approach that dynamically inserts the content into the page at runtime. The most common way to do this is to store the data in a database, which can be updated using a range of techniques when required. The web page will always show the latest version of the data.

WebMatrix includes a small and simple database application that you can use to store and expose data that changes, and which you want to be able to access in your website. The database is Microsoft SQL Server Compact Edition (usually referred to as SQL CE), which was originally developed for use in small devices such as personal digital assistants (PDAs) and mobile 'phones.

You saw the way that you can access a database in WebMatrix in the first task of this exercise. If you expand the App_Data folder when WebMatrix is in Files view, you see the database file named StarterSite.sdf. You can double-click this to switch WebMatrix to Databases view, or you can click the Databases option in the lower-left-hand panel of the WebMatrix window.

This displays the contents of the database, starting with a sub-item named Tables. Expand this to see the tables already in the database (shown in the following screenshot). These tables are used by the visitor registration mechanism that is included in the Starter Site template that you used to create your site. You will see more about these tables and visitor registration in a later exercise.

Note:

Data in a database is stored in separate tables. Each table stores data in a row and column format where the type of data in the cells of a row may differ, but the cells in a column all contain data of the same type. For example, a table may consist of multiple rows, each of which stores a name as a string value, an age as a numeric value, and a true/false value. You will see a lot more information about database tables throughout these exercises.

You can, if you prefer, create a separate new database for your website's data, but it makes sense to use the existing database. You can add new tables to it that contain the dynamic data you want to access in your site.

The Steps for Creating the News Items Database Table

Now that you understand how WebMatrix provides support for storing dynamic data in a database, you can go ahead and create a table that contains news items for display in the Home page of the site.

To create the news items database table

Continue with the SoccerWebsite site you created in the previous task. If you have closed WebMatrix, open the site. You can either:

Start WebMatrix, click the My Sites option in the opening screen, select the SoccerWebsite site in the list of recent sites, and click OK.

Navigate to your Documents\My Web Sites folder in Windows Explorer (in Windows 7, this is within the Libraries folder), right-click on the SoccerWebsite folder, and then click Open as a Web Site with Microsoft WebMatrix.

Click the Databases option in the lower-left panel of the WebMatrix main window. Expand the StarterSite.sdf item in the tree view, and then expand the Tables item to show the list of existing tables in the database.

Right-click the Tables item in the tree view and then click New Table. This opens the table designer in the main WebMatrix editor window. The upper section of the table designer window displays a list of the columns in the table, and the lower section displays the properties of the column selected in the upper section. At the moment, there is just a default single new column in the designer waiting for you to specify the column name and data type.

Note:

The new table will contain one row for each news item. Each of these rows will contain a series of columns that hold specific information about the news item in that row. The columns you will create are a primary key column that allows code to uniquely identify each row, and separate columns to store the data of the item, the title of the item, the text of the item, the name of an optional image file related to the item, and an optional URL that visitors can use to get more information about an item.

Select the single default row in the upper section of the table designer, then click in the text box next to the (Name) property in the lower section of the table designer. Type the name for this column: NewsId.

Note:

When choosing names for columns in a table, it is common to include the table name or some text that makes it easier to tell which table the column is in. This also makes creating queries easier, because there is less clashing of table names (for example, many tables could otherwise include a column named Quantity or Tax). In addition, it avoids the extra complexity caused by using column names that are also the names of functions or object properties (such as Name or Date).

To make this column into a unique identifier for the row, you must set the appropriate properties of the column. Change the Is Identity property to True to specify that this column will contain unique numeric identifier values for each row, and set the Is Primary Key property to True to specify that these unique identifiers are the primary and only key for the rows in the table. Notice that WebMatrix automatically sets the Allow Nulls property to False because null values are not valid in an identity column.

Now you can continue to add the columns required to the new table. Click the New Column icon in the toolbar ribbon to add a new column to the table

Set the name and other properties of the new column as shown in the following screenshot. The column name is NewsDate and it cannot contain null values. The data type for values in this column is datetime and the default value if one is not provided when a new row is added to the table is the current date returned from the getdate function.

Repeat the previous two steps to add the remaining columns to the new table. The remaining columns you require, and the properties for each one, are listed in the following table. Notice that the properties available for a column vary depending on the data type you specify for that column. Ensure that you enter the column names exactly as shown because you will later refer to the data in your code using these column names.

(Name)

Allow Nulls

Data Type

Default Value

Is Primary Key

Length

NewsTitle

False

nvarchar

False

4000

NewsText

True

ntext

False

NewsPictureURL

True

nvarchar

False

4000

NewsLinkURL

True

nvarchar

False

4000

Note:

It may seem extravagant to allow 4000 characters for the title and URLs in the table. However, the data type nvarchar will only allocate room in the database for the actual number of characters used, and so there is no wasted space. If we had specified the data type nchar with a fixed length, any value shorter than this would leave the remainder allocated even though it is not used.

After you specify all of the columns and their properties, click the Save icon at the left-hand end of the WebMatrix window title bar (shown in the following screenshot). In the Save Table dialog, enter the name NewsItems for the new table and click OK.

You will see the NewsItems table appear in the Table list in the left-hand tree view. Double-click on this to open the table data editor in the main WebMatrix editor window.

You can now edit the contents of the rows in the NewsItems table to create the news items. Do NOT type anything in the first column (NewsId) because this is the unique identifier column. The database will populate this column automatically as you add rows to the table. In addition, if you leave the NewsDate column empty (NULL) the database will automatically insert the current date. If you specify a date in this column, the database does not change the value. Experiment by adding a few rows. However, don’t spend too much time on this because we have provided a database with this table prepopulated for use in your site.

Click the small "x" on the Table - (StarterSite.sdf).NewsItems tab in the main editor window to close the data table editor.

In Windows Explorer, navigate to the \Examples\Exercise_01\Resources\NewsDatabase folder. Copy the file named StarterSite.sdf into the subfolder named App_Data of your Documents\My Web Sites\SoccerWebsite folder so that it replaces the existing file with the same name.

Note:

Note that the file copy dialog will warn you that the file you are replacing is newer than the one that will replace it. This is because you added the table to the existing database file, but you are now replacing it with the file containing the prepopulated NewsItems table that we provide in the samples.

Back in WebMatrix double-click the NewsItems table to re-open the table data editor. Now you will see the prepopulated rows in the table.

Note:

The format of the date displayed on your system will depend on your region settings. In addition, notice that the NewsId column values do not start at 1. When you add a new row, it takes the next available identifier value. When you delete a row, the identifiers of the other rows do not change (if they did, it would break any code that specifies a row using the identifier, and any links between tables that depend on the identifier values). Likewise, you cannot edit the values of these identifiers.

You have now completed this task, and you should have a broad understanding of how you can use a database to store dynamic data that you will display and use within your web pages. In the next task of this exercise you will display the data in the NewsItems table in your site's "Home" page.

Task 4 - Display the News Items

In this task, you will modify the Home page of the site to display the news items in the table you added to the database. You do this by adding code to the page that connects to the database and retrieves the required set of data rows from the NewsItems table, and then inserts the values from each row into the output generated by the page.

To display the news items in the Home page

Continue with the SoccerWebsite site you created in the previous task.

Click the Files option in the lower-left panel of the WebMatrix window, and then double-click the file named Default.cshtml to open it in the code editor. This is the Home page you have seen in previous tasks of this exercise.

Edit the existing code at the top of the page so that it sets the appropriate value for the Title property of the page, as shown in the following highlighted code.

Now replace the contents of the <p> element after this code section with something more appropriate. In our example, we added some text that explains what WebMatrix can do and describes the site we are building.

<p>This example site shows how you can use WebMatrix to quickly and easily create useful and interactive Web sites. This site provides features for a junior soccer team to display information such as the matches they play, the results, and the teams. It also makes it easy for parents to arrange rides to matches, and see how well their team is doing in their league.</p>

Next, add the header for the news item list (below the site description you just added) as an <h2> element, as shown in the following code.

You should always try to use the HTML header elements (<h1> to <h6>) for headers in order to apply structure to your content, and so that it can easily be parsed by mechanized tools such as search engines that can then gather context for the content. If you only use <p> or other elements for headings (even if you style them using CSS to give the required appearance) tools and user agents that do not load or read the style sheet will not be able to tell which are actually headings that provide context and structure.

To connect to and open a database and then read the contents of a table you must write some code in the page. WebMatrix provides a class named Database that exposes methods you can use for these tasks. Add the following code to your page after the "Recent News" heading, remembering to include the @ character that defines the start of a code block, and the curly braces that enclose the code.

This code opens the StarterSite.sdf database file by referring to it using just the database name (this works because the database is located in the App_Data folder), and stores a reference to it in the variable named db. There are other ways you can connect to and open a database, which are appropriate if you use a separate database for your site data. For more information, see the section "Connecting to a Database" at the end of the topic "Tutorial - Working with Data" on the official ASP.NET website at http://www.asp.net/webmatrix/tutorials/5-working-with-data.The code above then executes the Query method of the Database class, passing to it a SQL statement that selects all of the columns for all of the rows in the NewsItems table and sorts the results in descending order based on the values in the NewsDate column. The set of rows returned by the query are stored in the variable named news. A reference to SQL can be found at "Transact-SQL Reference" on MSDN at http://msdn.microsoft.com/en-us/library/ms189826(v=SQL.90).aspx.

The next step is to iterate over the set of rows returned by the SQL query in the variable named news. Add the following definition of a <div> element with the identifier news-items to the end of your page. Within the <div> element, add a code block that will be repeated once for each row in the results set. As it iterates over the rows, the foreach statement will assign each one to the variable named newsItem.

As you've seen previously, the @ character indicates the start of a code statement. The page parsing engine treats everything after this as code to be executed until it finds a character that cannot be part of the code. In this case the foreach statement is followed by a set of curly braces that enclose lines of executable code, but the < character at the start of the closing <div> tag indicates to the page parsing engine that this and subsequent content in HTML and not code.

Now you can add some code that will take the values of the columns in the current row and display them in the page. Start by adding an <h3> element (remember that we are aiming to create the appropriate document structure using nested headings). Within the heading element, add code that retrieves the value in the NewsDate column and formats it as a "short" date (such as "10/6/2011"), followed by the value from the NewsTitle column of the current row. The code you need to add is highlighted in the following listing.

Notice that the <h3> element includes a class attribute that specifies the style class news-header. If you examine the site style sheet (Site.css) you will see that it doesn't contain a definition for a class named news-header. This does not produce an error, because the browser simply cascades and applies the style of the parent element (in this case, the body of the page) to this element. However, by including a class attribute, we allow future changes to the site appearance to include a definition of a set of CSS selectors with the name news-header, which will then automatically be applied to every instance of this element (remember that there will be one for each row in the rowset of news items).

Now that you have created a heading for every news item in the rowset, you can continue by adding the code to display the details of each item. Add a <div> element that will enclose all of the details of the current news item and, within this, another <div> that will display the text of the news item by accessing the value in the NewsText column, as shown in the following highlighted code.

Each news item row may also contain the name of an image associated with the item, and a link for more information about the item. Add the following highlighted code that checks if there is a value for the NewsPictureURL column in the current row and, if there is, generates an <img> element with a href attribute that points to the picture (which will be in the news-images folder). The highlighted code includes a <br> element with the clear="all" attribute to ensure that each news item will start a suitable distance below the previous one, even when the text is wrapped around an image.

You can see in the code above how the page executes an if statement that calls the static IsNullOrEmpty method of the String class to see if there is a value for the NewsPictureURL column in the current row, and the Href method to generate the appropriate URL for the src attribute of the <img> element. Notice that the <img> element also includes an alt attribute containing the title of the news item. This will be displayed in browsers or specialist user agents that do not support images.

The last item of information for a news item is the optional link to more information. Add the following highlighted code to your page that checks if there is a value for the NewsLinkURL column in the current row and, if there is, generates an <a> (hyperlink) element with a href attribute that points to the value in the NewsLinkURL column. You want the linked page to open in a new browser window, so the <a> element includes the attribute target="_blank".

You've added code to display an image where the row includes an image filename, but at the moment you have no images. We provide a set that matches the news items in the NewsItems table of the sample database. In Windows Explorer, navigate to the folder \Examples\Exercise_01\Resources. Copy the entire subfolder named news-images and its content into your Documents\My Web Sites\SoccerWebsite folder.

Back in WebMatrix click the Stop icon in the toolbar ribbon. Then right-click the top-level SoccerWebsite item in the left-hand tree view and click Refresh. You will see the news-images folder appear in the tree view.

You can now run the page to see what it looks like (and check you have entered all of the code and HTML correctly). Select the file Default.cshtml in the tree view, and then click the Run button on the toolbar ribbon. The following screenshot shows the first of the news items that are displayed.

Note:

Notice that the text is below the image (the default layout for the HTML we used). It would be nice to wrap it to the right of the image. The correct way to achieve this is to use CSS, rather than applying deprecated HTML attributes such as align="middle" directly to the image element. And, of course, using CSS also makes future changes to the layout much easier.

Close your browser and, in the tree view pane of WebMatrix, expand the Styles folder and then double-click the style sheet file named Site.css to open it in the editor.

Scroll down to the section marked with the comment /* Login Display and insert the following style definition just before it. This sets the style for any <img> element that carries the attribute class="newsimage" so that it floats to the left (allowing text to wrap to the right of the image), has a 15 pixel wide margin at the right and bottom where it meets the text, and a thin black border 5 pixels away from the edges of the image.

In general, the order of the style definitions in a style sheet is not important except where they refer to the same elements (in other words, where the styles cascade so that an element may match more than one style definition). When this occurs, the last definition takes precedence. This is why it's common to define the general style settings, such as those for the body and headings, at the start of a style sheet.

Save the Site.css file and run the page again to see the change due to the new style definitions. Select the file Default.cshtml in the tree view, and then click the Run button on the toolbar ribbon. The following screenshot shows three of the news items with the text wrapped to the right of the image.

You have now completed this task, and you should understand the basic approach to retrieving data from a database and displaying it in a web page using WebMatrix. In the next and final task of this exercise you will modify the page to add some client-side interactivity by converting the news items into separate expandable sections rather than just displaying them as a static list.

Task 5 - Add Client-side Interactivity to the Page

In this task, you will modify the page to add some client-side interactivity by converting the news items into separate expandable sections rather than just displaying them as a list. Whilst the page is complete and working fine, it is still a static page. Even though you have used dynamic techniques to build the content that visitors see at runtime from data stored in a database, the content itself is static in that the user can only view the output you generated.

This may be all you want to achieve, but increasingly visitors expect sites to appear to be dynamic within the browser. For example, it is common for sites to offer scrolling menus, expanding sections of content, and other interactive features. All of these can be accomplished by several different technologies, such as ActiveX controls, Java applets, Flash animations, and more. However, the most common approach, and the one that has widest support across different browsers and user security settings, is the use of client-side JavaScript and the functionality provided by jQuery libraries.

Using JavaScript and jQuery in a Web Page

JavaScript has been a feature of most web browsers since the mid 1990's, and is still a common approach for adding client-side interactivity to a web site. However, accessing the contents of a page, animating it, and producing attractive and useful effects generally require a great deal of JavaScript code. It also requires familiarity with the specific anomalies of each browser type, with a corresponding increase in the code required to manage these differences.

Most web sites now take advantage of prebuilt libraries of code to achieve the client-side effects they require. The most common of these today is jQuery, which provides supports for a wide range of interactive effects in all of the popular web browsers. Typical examples of the effects they provide include access to elements within the HTML of the page so that they can be manipulated (such as changing the style or position); functions that provide complex animation such as fading and sliding sections of the page; functions for managing errors and handling events; functions for working with data and communicating with the server in the background; and much more.

You can obtain jQuery libraries from a range of sources. The examples we provide use the open source implementation provided by Microsoft. For information about jQuery, a tutorial for using it, and to download the library, see the jQuery home page at http://jquery.com/.

You can use a Content Delivery Network (CDN) site that hosts the jQuery files to deliver them to your visitors' web browser. This saves you from including it with your site's files, and can also reduce bandwidth and load time for your site because the visitor may already have this cached in their browser if they have previously visited another site that uses it. For more information, see "CDN Hosted jQuery" at http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery.

Alternatively, you can simply place the jQuery library code in a folder of your site and reference it in pages that use it. Then you can call the functions in the library from script within your web pages to apply the effects or to make use of the functionality it provides. This provides a consistent codebase, but you are then responsible for managing updates to newer versions if you need additional features added to jQuery in the future. In the example described here you use a jQuery file we provide, and has been tested with the code used in the example (which also means that you can run the example without requiring a connection to the Internet to download the file).

The Steps for Adding jQuery Interactivity to the Site

The following procedure shows a basic technique for using jQuery to animate the news items in the Home page of the SoccerWebsite site you have been creating in the previous tasks of this exercise.

To create expanding sections for each news item

Continue with the SoccerWebsite site you created in the previous task.

The first step is to add the jQuery library to the site. You can download it from the jQuery website referenced earlier in this task description, though we also include it in the examples. In Windows Explorer, navigate to the folder \Examples\Exercise_01\Resources. Copy the file named jquery.js into your Documents\My Web Sites\SoccerWebsite folder.

Back in WebMatrix click the Stop icon in the toolbar ribbon. Then right-click the top-level SoccerWebsite item in the left-hand tree view and click Refresh. You will see the file jquery.js appear in the tree view.

To load the jQuery library into your pages, you use a <script> element. As it is likely to be used in many of the pages, it makes sense to locate this in the master (site layout) file. As you saw in Task 2 of this exercise, the content of this file appears in all pages that use it. In the left-hand tree view, double click the file named _SiteLayout.cshtml to open it in the WebMatrix editor.

Find the <head> section and add the following highlighted line to it. This causes the browser to load the jQuery library from the root folder of the site (even when the current page is in a subfolder of the site) and make it available in the page. As a bonus, the browser will usually cache the file on the visitor's computer, and so it will only be downloaded once from your site.

Save and close the _SiteLayout.cshtml file. Then, in the tree view, double-click the file named Default.cshtml to open it in the WebMatrix editor.

Add the following code to the end of the Default.cshtml page. This is client-side JavaScript code that makes use of the jQuery library functions to allow the user to expand and contract each news item in the list on this page.

While the steps you have followed so far are sufficient to implement the expanding sections, there are some other changes required to make the page more intuitive. For example, a visitor looking at the page will now see only a list of news titles with a date but no text or photo. They may not realize that they have to click on one to show the details. Click the Run button on the toolbar ribbon and hover your mouse pointer over the news item titles. As you can see from the screenshot here, there is no indication that each one is a link. The mouse pointer shows as an I-beam (text edit) cursor, just as it does when over ordinary static text within the page.

To fix this you will make each title show an underline when you hover over it, and change the mouse pointer to the familiar "hand" that indicates an item is "clickable". Close your browser and, in the left-hand tree view pane of WebMatrix, expand the Styles folder and double-click the file named Site.css to open it in the editor.

Scroll down to the section with the comment /*News page that you added to the style sheet in the previous task. Insert the following highlighted CSS style definitions to this section.

The first of these style definitions specifies that the browser should display a pointer ("hand") cursor when over elements that carry the attribute class="news-header". These are the <h3> elements that display the date and title of each news item. The second style definition specifies the text decoration for these <h3> elements when the mouse pointer hovers over them. It simply changes the style of the text so that it is displayed with an underline (which suggests to visitors that it is a clickable link).

Save the style sheet and close it; then select Default.cshtml in the tree view and click the Run button on the toolbar ribbon. You will see that the news titles now appear with an underline and a pointer icon when you hover over them with the mouse.

Click on the news item headings and see how they slide/expand to show the details, then slide closed when you click the heading again. All of this magic is generated within the jQuery library. You can see how complex and attractive dynamic effects like this are easy to achieve by taking advantage of the power of a jQuery library. And this is just a simple example. You will see more in later exercises.

How the JavaScript and jQuery Code Works

The JavaScript code you have added to the page in this task (repeated below) defines a handler that is executed when the page loads into the visitor's browser. It handles the event that is raised when the document (the web page) has finished loading and is ready to handle user interaction.

The function executed when this event occurs references all instances in the document of elements that carry the attribute class="news-header" and which are also children of an element that carries the attribute id="news-items". To make it easier to see, we list below the section of code that you added to the Default.cshtml page in the previous task to display the news items.

You can see in this code that the single <div> that contains all of the news items carries the attribute id="news-items". Each of the news items within this <div> has an <h3> element that carries the attribute class="news-header" and displays the date and title of each news item.

Therefore, the following line of JavaScript code specifies a function (handler) that will be executed only when a visitor clicks on any of the news titles:

The body of the function executed for the click event uses the jQuery function named next to get a collection of all of the elements that follow the current element (the <h3> element containing the title) within the current parent element (the <div> element with id="news-items"). It then calls the toggle method for each of these elements, and returns false so that the browser will not execute any other code in response to the click occurring in the page.

In the code in your Default.cshtml page, there is only one element after the <h3> title element in each news item: the <div> with class="news-body". Therefore, when a visitor user clicks the title of a news item, the code you've just seen will toggle the expansion of just this <div>. However, expanding or contracting an element automatically includes all of its child elements: in this case the image, the text of the item, and the link for more information.

There is one more feature of the code to examine. After defining the event handler for the click event, the code continues by executing the jQuery next method for each of the news item <h3> elements, and calling the hide method of their child elements (the <div> elements with id="news-body").

This is necessary because, by default, the news items are displayed in the default (expanded) state when the page first loads. You may just be able to detect this when you run the page in your browser the first time as by the screen flicker as it loads and caches the news item images. Once the document has loaded, the news items are collapsed (hidden) so that only the titles are visible. This also means that, in specialist user agents that do not support JavaScript and browsers where the user has disabled scripting, the news items will still be visible because they will not be automatically collapsed after the page loads.

The following screenshot shows the final result from all of the tasks in this exercise, with one of the news items expanded.

You have now completed this task and this exercise. You should now be comfortable with using WebMatrix to create a simple Web site, apply your own styles and change the appearance, and create content dynamically using a database. In later exercises you will add more pages to the site, and see more examples of building web pages using WebMatrix and jQuery.