ASP.NET 2.0 CSS Friendly Control Adapters: The Walkthrough

Summary

This is a step-by-step tutorial of how to install and use this sample kit. Please refer to this kit's white paper for more information.

Introduction

Relax. This tutorial is going to explain everything. You'll soon discover the power of ASP.NET 2.0 control adapters. In particular, we'll look at how adapters can help you create an ASP.NET 2.0 web site that uses more CSS and renders fewer (and better) <table> tags.

This tutorial moves you through the following tasks, building upon each in turn.

Download and Install this Sample Kit

This sample kit can be run on any computer where Visual Web Developer or Visual Studio 2005 is installed.

Using any web browser, visit http://www.asp.net/cssadapters/ and click the download source button.

The Kit's Home Page

Click the Open button to download and run this sample kit's VSI file.

The File Download dialog

The Visual Studio Content Installer will add several new web site templates to Visual Studio. You'll learn more about these templates when you build a web site that can be run locally.

The Visual Studio Content Installer Visual Studio Content Installer - click Finish

If you've installed this kit previously, you'll be asked if the old version can be overwritten.

Visual Studio Content Installer - it's okay to overwrite the existing files

Click the Close button when the VS Content Installation completes.

Visual Studio Content Installer - Complete

Run a Local Copy of the Kit

Create a new web site within Visual Studio using the File > New Web Site ... menu command.

Create a new website

The New Web Site dialog provides a variety of templates to get you started.

After completing this tutorial you'll be ready to create new web sites that use these CSS Friendly control adapters. The template named ASP.NET CSS Friendly Web Site is ideal for that task. It contains just the adapter files plus a small handful of simple sample pages that you can clone or modify.

First, though, it's important to learn about adapters in general and the CSS Friendly sample adapters in particular. So, you will want to select the template named Tutorial on ASP.NET CSS Friendly Control Adapters. It will create a somewhat more complex web site intended to help you learn about adapters. Remember that you'll want to use the slimmer ASP.NET CSS Friendly Web Site web site template when you are ready to do your own development. The tutorial template is provided simply to speed the learning process.

Specify a Location and Language for the site and then click OK.

Create the new site using the CSS Adapter Template

This will create a copy of this sample kit's web site on your local computer. In a moment you'll run this local web site using Visual Studio's built-in Cassini web server. First, though, you should take a quick look at the notes found in the readme.txt file that appears when you first create this local web site.

Be sure to read the readme.txt file

The Solution Explorer lists the files created. To see a detailed discussion of the files and folders created, please see Explore the Files in the Kit. The rest of this section shows you how to view the kit's pages in a browser and highlights some interesting features.

Files created using the CSS Adapter Template

Click the Start Debugging button on Visual Studio's toolbar or use the menu command Debug > Start Debugging.

Run the web site

In order to run these web pages locally on your PC you need a web server. Visual Studio uses a light-weight web server called Cassini. It will be running as a result of your having told Visual Studio to start running your local version of this kit. The Cassini icon should be visible in your Windows task tray. And, when the browser starts, you'll see the port number used by Cassini displayed in the browser's address bar.

Using Cassini to serve the pages

Now let's take a look at some of the files in the kit. Sample pages for each of the adapted controls are listed in the menu at the top of the page, under Examples. This is your first chance to use an adapted <asp:Menu> control. It uses nested <ul> rather than <table> tags.

Main navigation menu for the kit

Now go to the Menu example page. It will help us see more clearly how page that use adapters differ from those that don't.

Navigating to the Menu sample

All the sample pages in the kit are organized alike. Each has a working example of a particular control whose resultant HTML is shown in a pair of "snippets" at the bottom of the page. The snippet on the left shows the HTML sent to the browser by the control adapter. The snippet on the right shows the unadapted HTML that is produced by the ASP.NET 2.0 framework. Radio buttons that appear on the left side of each sample page let you see what happens if you turn off the sample adapter or swap in a new set of CSS rules (a different theme).

Layout of the kit's sample pages

Each sample page can be run with or without the adapters by setting the radio button labeled Use Adapters?.

Enable/disable adapters

The "acid test" for CSS is altering the appearance of that web site merely by swapping style sheets and images without touching the HTML markup. You can test these sample pages by switching between themes.

Use the Theme Chooser to switch style sheets. Two themes are provided: Basic and Enhanced. There is one set of style sheets for the Basic theme. There's another set for the Enhanced theme. They live in the folders below App_Themes.

Set the Theme Chooser to None to decouple the page from all its style sheets. Ideally, the markup should look simple. Try this with and without the adapters enabled.

The screenshots below show the sample <asp:Menu> control styled with the Basic and Enhanced themes. The last screenshot shows the page decoupled from its style sheets.

The Theme Chooser

To see how each sample is implemented click the view source code button. This will show a simple but effective code viewer, included with the kit. It not only helps you examine the code for each sample but can be studied as a sample itself. After all, the code viewer page also uses an adapted <asp:TreeView> control.

Layout of the source code viewer page

Explore the Files in the Kit

There are three kinds of server-side ASP.NET 2.0 code used by this sample web site:

  • Code behind files with logic for individual pages. The found in the same folder as the page (ASPX file). For example, the menu sample page for this kit is Menu.aspx. It is found in the root folder for this web site. That same folder contains that page's code behind file (Menu.aspx.cs or Menu.aspx.vb). Other pages may be found in the Membership and WalkThru folders.
  • Code that helps these samples run but probably won't be useful in other web sites. For example, these samples use a fake membership provider in lieu of a real membership system that would typically use a database. This sort of logic is stored in files in the App_Code\SiteSpecific folder.
  • Code for the sample CSS Friendly adapters. This is code that you may want to use in your web sites, too. For example, the adapter for the TreeView control is TreeViewAdapter.cs/TreeViewAdapter.vb. These files are kept separate from the other parts of the web site so you can find them easily. Look for the files in the App_Code\Adapters folder.

Files in the App_Code folder

ASP.NET 2.0 introduces the notion of Themes. These are merely subfolders below the App_Themes folder. These theme folders are where you put the style sheets and images that are unique to one particular "look" for your pages. An ASP.NET page indicates its theme, typically, in its @Page directive. This tells the ASP.NET framework which theme folder should be used. When the page is rendered to the browser its <head> automatically includes <link> tags for each CSS file found in the theme folder used by that page.

Each of the adapted controls in the kit has its own style sheet. For example, the <asp:GridView> control has a style sheet named GridViewSample.css. The kit contains two themes: Basic and Enhanced. Therefore, the kit has a GridViewSample.css file in the Basic folder and another in the Enhanced folder.

Folders and files in the App_Themes folders

The bin folder for this sample kit includes a copy of Wilco Bauer's handy utility for displaying highlighted markup and code on ASP.NET pages. This has nothing to do with the adapters. It is used whenever markup or code is described in the documentation in this kit.

The files in the bin folder

Some of the pages in this kit use sample data stored in XML files. These kit-specific data files are stored in the App_Data folder. You probably won't need to use these files in your web sites. For example, Contacts.xml is used as the data source for the three sample pages highlighted below.

The Contacts.xml file is the data source for three sample pages

Previously, you saw that style sheets and images that constitute the "look" for your pages should be put in a particular theme subfolder below App_Themes. In addition, there are style sheets that are used by the adapters without regard to the current theme. These special style sheets contain rules that govern the behavior of the adapted controls, not their appearance. For example, when implementing a pure CSS menu, there are some rules that govern the color, font, etc. for the menu items but there are other rules that govern how the menu fundamentally works, how its submenus appear and disappear depending on whether or not you hover your cursor over parts of the menu, etc. These are the sort of rules that you find in the style sheets in the CSS folder and in its subfolder that contains browser-specific behavioral rules.

The CSS folder The browser specific CSS files

Your web site can be configured to always use these control adapters, regardless of what kind of browser is used to visit your pages. Or, you can fine tune your configuration so the adapters are used only with specific versions of specific browsers. Either way, if you want to use control adapters in your site then it must include a folder in its root called App_Browsers. Any file with the extension .browser that is in the App_Browsers folder is used by the ASP.NET framework to specify how your pages should respond to various browsers.

This sample adapter kit comes with a .browser file called CSSFriendlyAdapters.browser that lives in the App_Browsers folder. It configures the web site to use the CSS friendly adapters by default. You can, of course, modify this by changing the refID value to IE6to9, Gecko, Opera8to9, etc.

The kit's .browser file

A few of these sample adapters require a small amount of JavaScript. The kit puts this client-side logic into JS files in a folder called JavaScript. For example, TreeViewAdapter.js. However, you can customize this folder location by changing the CSSFriendly-JavaScript-Path key in the appSettings section of the site's web.config file.

The files in the JavaScript folder

A subset of this kit is devoted to demonstrating how to adapt the various membership controls in the ASP.NET 2.0 framework. The pages used as examples for these adapted controls are in the Membership folder. For example, the login page.

The sample pages in the Membership folder

Experiment with Changing the Kit's CSS

At this point you've installed and run these samples locally. You've looked over the organization of the web site's files. Ultimately though, you'll want to clone and modify these files to create your own designs in your own web sites. Let's start by making a very small modification to these sample pages to gain confidence that we can successfully customize and change things. This will be our first step towards bigger, more challenging tasks like adding these sample adapters to entirely new web sites.

We're going to modify the sample menu to use a different shade of blue for the background items being hovered over.

In Visual Studio, open the file App_Themes\Basic\MenuExample.css. Find this rule:

CSS
1
2
3
4
5
6
.PrettyMenu ul.AspNet-Menu li:hover, 
.PrettyMenu ul.AspNet-Menu li.AspNet-Menu-Hover
{
    background:#4682B3;
}

Change the color value to something different, like #27408B. Save the style sheet and refresh the menu sample page. The new color should appear when you hover over the sample menus.

The menu sample with the original and new background hover color

For parity in situations when the adapters are not used, you should also modify the skin file used for the Basic theme. Open the file App_Themes\Basic\Basic.skin. Locate the two DynamicHoverStyle tags whose BackColor attribute is #4682B3. Change this to your new color (like #27408B).

The Basic.skin file

Build a Simple Page that Can Use the Kit's Adapters

The code block below is the skeleton of the page that is ready to use the sample adapters included in this kit. The @Page directive declares the Language used by the page but does not mention theme, master page, code behind file, inherited class, etc. Our intent is to examine a simple page that uses these sample adapters. The pages in this kit that you visit via the Examples menu, by contrast, use master pages and other complexities that can make it more difficult to see the bare skeleton of the page that is really needed to accommodate these sample adapters. That is what we will look at now.

Within the <head> the page links in several style sheets. The first imports the theme-independent style sheets that dictate the behavioral CSS rules for each sample control adapter (e.g., Menu.css). You will rarely (if ever) need to change the rules in these styles sheets. Generally, you link them in and forget about them.

The page also conditionally links to a style sheet needed by previous versions of Internet Explorer (IEMenu6.css).

The rest of the page is a standard, empty ASP.NET page. You would normally start adding your markup within the server-side form (or its inner <div>).

ASP.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    <%@ Page Language="C# or VB" %>    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <link runat="server" rel="stylesheet" href="~/CSS/Import.css" type="text/css" id="AdaptersInvariantImportCSS" />
        <!--[if lt IE 7]>
            <link runat="server" rel="stylesheet" href="~/CSS/BrowserSpecific/IEMenu6.css" type="text/css" id="IEMenu6CSS" />
        <![endif]--> 
    </head>
    <body>
        <form id="form1" runat="server">
            <!-- adapted control(s) here-->
        </form>
    </body>
    </html>

The files the kit's WalkThru folder use this page structure.

Make a "Pure CSS Menu" with an Adapter for <asp:Menu>

click to run the exampleSimpleMenu.aspx

Menus on web sites tend to have one of two goals:

  • Navigate to various pages in the site.
  • Postback to the current page indicating that a particular menu item was chosen.

Earlier versions of this sample kit included an adapter for the <asp:Menu> control that supported the first goal: navigation to an explicit URL. This is, of course, still supported in the current version of the kit. Now, though, the adapted <asp:Menu> supports the second goal, too. That is, the sample adapter can be used to create menus that postback. A simple example of this is found in WalkThru\SimpleMenu.aspx.

The SimpleMenu.aspx page

Here is the <asp:Menu> markup used in SimpleMenu.aspx. The menu items do not set the NavigateUrl property so the adapter assumes that the page should postback. The "Movie" node is marked as being unselectable, which means that it does not cause a postback or any navigation. Finally, notice that a server-side event handler is used to process click events. With few exceptions, server-side events are handled by the framework regardless of whether or not an adapter is being used. In this example, the server-side event handler updates a label to demonstrate that the selected menu item is known. Presumably, in your own web sites, such a handler would do much more inventive and useful things!

ASP.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<asp:Menu ID="EntertainmentMenu" runat="server" Orientation="Horizontal" onmenuitemclick="OnClick" CssSelectorClass="SimpleEntertainmentMenu">
    <Items>
        <asp:MenuItem Text="Music">
            <asp:MenuItem Text="Classical" />
            <asp:MenuItem Text="Rock">
                <asp:MenuItem Text="Electric" />
                <asp:MenuItem Text="Acoustical" />
            </asp:MenuItem>
            <asp:MenuItem Text="Jazz" />
        </asp:MenuItem>
        <asp:MenuItem Text="Movies" Selectable="false">
            <asp:MenuItem Text="Action" />
            <asp:MenuItem Text="Drama" />
            <asp:MenuItem Text="Musical" />
        </asp:MenuItem>
    </Items>
</asp:Menu>

It's possible visually distinguish the selected menu item, its parents or children using an adapted <asp:Menu> control. The adapter automatically adds a class called .AspNet-Menu-Selected on the anchor tag within the <li> tag that is rendered for the selected menu item. The anchor in the <li> tag that is "above" this selected menu item in the hierarchy is similarly flagged; this time with the .AspNet-Menu-ParentSelected class. Likewise, the anchors in the submenus of the selected menu item are classed as .AspNet-Menu-ChildSelected. With these classes in mind you can use CSS to visually distinguish these parts of the menu.

CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 .SimpleEntertainmentMenu .AspNet-Menu-Selected
{
    border: solid 1px #00ff00 !important;
}

.SimpleEntertainmentMenu .AspNet-Menu-ChildSelected
{
    border: solid 1px #ff0000 !important;
}

.SimpleEntertainmentMenu .AspNet-Menu-ParentSelected
{
    border: solid 1px #0000ff !important;
}

These CSS rules produce the visual cues shown in the menu below. You may wish to use other CSS properties, instead, like background color, font family, etc. Changing the border color is merely an easy way to demonstrate the concept here.

The SimpleMenu.aspx page.

Add a Simple Adapted <asp:TreeView> to a Page

run the exampleSimpleTreeView.aspx

The kit's WalkThru folder includes a SimpleTreeView.aspx page. It is very similar to the SimpleMenu.aspx page but presents the data as a tree, instead of a menu.

The SimpleTreeView.aspx page showing postback

Like the menu adapter, the sample adapter for the TreeView control uses CSS classes to distinguish the selected node, its parents and children. These classes can be optionally defined in your style sheets to provide visual cues that quickly bring the user's eye to the most important portions of the tree.

The SimpleTreeView.aspx page showing selected node styling

Populate-on-demand an Adapted <asp:TreeView>

run the examplePopulateOnDemandTreeView.aspx

A TreeView is sometimes used to display vast hierarchies of information. For example, a large company might show its employee directory as a tree whose first branches indicate the continent, country and region where the employee works. Rather than building the page with a tree immediately capable of showing all the employees you might wish to initially show just the continents (the first set of tree nodes). If one of these nodes is expanded, the page would postback to the server to fill in the countries where the company has offices. Likewise, expanding the node in the tree for a country would postback to get the nodes for the regions within that country, and so on.

The TreeView in the ASP.NET 2.0 framework includes this sort of populate-on-demand feature. The sample CSS Friendly adapter for the TreeView now provides this functionality, too. The WalkThru folder includes a PopulateOnDemandTreeView.aspx page to get you started.

The PopulateOnDemandTreeView.aspx page showing populate-on-demand

Add Checkboxes to an Adapted <asp:TreeView>

run the exampleCheckboxTreeView.aspx

Not only can a TreeView help you present complex hierarchical data, it can offer your visitors a way to choose one or more of those nodes. This is done by adding a checkbox next to particular nodes in the tree. The ASP.NET 2.0 framework includes this ability for the unadapted TreeView control; the sample CSS Friendly TreeView adapter offers this same ability, now, too. The CheckboxTreeView.aspx sample in the WalkThru folder shows you how this is done.

The CheckboxTreeView.aspx page

Cascade Checkmarks in an Adapted <asp:TreeView>

run the exampleCascadingCheckboxTreeView.aspx

A checkbox accompanying an expandable tree node suggests a quick way to set the checkmarks on all the child nodes at once. A parent node's checkmark can appear to cascade to its children. Clever people have published the JavaScript needed to accomplish this cascade. Still, the adapted TreeView needs to somehow know to use that JavaScript.

For this, the TreeView adapter includes a new (expando) property called OnClientClickedCheckbox. Add it to your <asp:TreeView> tag and set its value as a string of JavaScript to be executed in the browser (on the client) when a checkbox in the tree is checked or unchecked.

The CascadingCheckboxTreeView.aspx and its accompanying CascadeCheckmarks.js demonstrate this idea.

The CascadingCheckboxTreeView.aspx page