Article

ASP.NET 2.0: A Getting Started Guide

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Master Pages

Master pages are a new feature of ASP.NET 2.0 that can make an important difference in the way we compose web forms. Master pages are similar to web user controls in that they are also composed of HTML and other controls; they can be extended with the addition of events, methods, or properties; and they can't be loaded directly by users--instead, they're used as building blocks to design the structure of your web forms.

A master page is a page template that can be applied to give many web forms a consistent appearance. For example, a master page can set out a standard structure containing the header, footer, and other elements that you expect to display in multiple web forms within a web application.

Master page files have the .master extension, and, just like web forms and web user controls, they support code-behind files. All master pages inherit from the class System.Web.UI.MasterPage.

Designing a site structure using master pages and web user controls gives you the power to easily modify and extend the site. If your site uses these features in a well-planned way, it can be very easy to modify certain details in the layout or functionality of your site, because updating a master page or a web user control has immediate effects on all the web forms that use the file.

As we've already mentioned, a master page is built using HTML and controls, including the special ContentPlaceHolder control. As its name suggests, the ContentPlaceHolder is a placeholder that can be filled with content relevant to the needs of each web form that uses the master page. In creating a master page, we include all of the basic structure of future pages in the master page itself, including the <html>, <head>, and <body> tags, and let the web forms specify the content that appears in the placeholders.

Let's see how this works with a simple example. Suppose we have a site which has many pages that contain a standard header, footer, and navigation menu, laid out as per the wireframe shown in Figure 4.11.

1556_fig-basicpagelayout
Figure 4.11. A simple web site layout

If all the pages in the site have the same header, footer, and navigation menu, it makes sense to include these components in a master page, and to build several web forms that customize only the content areas on each page. We'll begin to create such a site in Chapter 5, Building Web Applications, but let's work through a quick example here.

To keep this example simple, we won't include a menu here: we'll include just the header, the footer, and the content placeholder. In your Learning folder, create a new file named FrontPages.master, and write the following code into it:

Example 4.26. FrontPages.master (excerpt)                    
                   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                    
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                    
<html>                    
 <head>                    
   <title>Front Page</title>                    
 </head>                    
 <body>                    
   <form id="myForm" runat="server">                    
     <h1>Welcome to SuperSite Inc!</h1>                    
     <asp:ContentPlaceHolder id="FrontPageContent"                    
         runat="server" />                    
     <p>Copyright 2006</p>                    
   </form>                    
 </body>                    
</html>

The master page looks almost like a web form, except for one important detail: it has an empty ContentPlaceHolder control. If you want to build a web form based on this master page, you just need to reference the master page using the Page directive in the web form, and add a Content control that includes the content you want to insert.

Let's try it. Create a web form called FrontPage.aspx, and add this code to it:

Example 4.27. FrontPage.aspx (excerpt)                    
                   
<%@ Page MasterPageFile="FrontPages.master" %>                    
<asp:Content id="myContent" runat="server"                    
   ContentPlaceHolderID="FrontPageContent">                    
 <p>                    
   Welcome to our web site! We hope you'll enjoy your visit.                    
 </p>                    
</asp:Content>

You're all set now! Loading FrontPage.aspx in your browser will generate the output shown in Figure 4.12.

1556_0435_MasterPage
Figure 4.12. Using a master page

Although the example is simplistic, it's easy to see the possibilities: you can create many web forms based on this template very easily. In our case, the master page contains a single ContentPlaceHolder, but it could have more. Also, the master page can define some default content for display inside the ContentPlaceHolder on pages whose web forms don't provide a Content element for that placeholder.

Using Cascading Style Sheets (CSS)

It's clear that controls make it easy for us to reuse pieces of functionality in multiple places. For example, I can't imagine an easier way to add calendars to many web forms than to use the Calendar web server control.

However, controls don't solve the problem of defining and managing the visual elements of your web site. Modern web sites need constant updating to keep them fresh, and it's not much fun editing hundreds of pages by hand just to change a border color, for example, and then having to check everything to ensure that the changes are consistent. The process is even more painful if the client wants a more serious update, like rearranging components on the pages.

The good news is that this maintenance work can be made a lot easier by planning ahead, correctly following a few basic rules, and efficiently using the tools HTML and ASP.NET offer you.

An essential tool for building reusable visual styles is CSS (Cascading Style Sheets). HTML was initially designed to deliver simple text content, and paid little attention to the specifics of how particular items appeared in the browser. HTML left it to the individual browsers to work out these intricacies, and tailor the output to the limitations and strengths of users' machines. While we can change font styles, sizes, colors, and so on using HTML tags, this practice can lead to verbose code and pages that are very hard to restyle at a later date.

CSS gives web developers the power to create one set of styles in a single location, and to apply those styles to all of the pages in our web site. All the pages to which the style sheet is applied will display the same fonts, colors, and sizes, giving the site a consistent feel. Regardless of whether our site contains three pages or 300, when we alter the styles in the style sheet, our changes are immediately applied to all pages that use the style sheet.

Look out for Themes and Skins
ASP.NET 2.0 provides extra value and power to those building reusable visual elements through its offerings of themes and skins. You'll learn more about these features in Chapter 5, Building Web Applications.

Types of Styles and Style Sheets

There are three different ways in which we can associate styles to the elements of a particular web page:

1. Using an external style sheet

By placing your style rules in an external style sheet, you can link this one file to any web pages on which you want those styles to be used. This makes updating a web site's overall look a cakewalk.

To reference an external style sheet from a web form, insert the following markup inside the head element:

<link rel="stylesheet" type="text/css" href="file.css" />

In the above example, file.css would be a text file containing CSS rules, much like the example shown below:

a                    
{                    
 background: #ff9;                    
 color: #00f;                    
 text-decoration: underline;                    
}

2. Using an embedded style sheet

You can place style rules for a page within <style type="text/css"> tags inside that page's head.

<style type="text/css">                    
 a                    
 {                    
   background: #ff9;                    
   color: #00f;                    
   text-decoration: underline;                    
 }                    
</style>

The problem with using these "embedded" styles is that we can't reuse those styles in another page without having to type them in again, which makes global changes to the site very difficult to manage.

3. Using inline style rules

Inline styles allow us to set styles for a single element using the style attribute. For instance, we might give a paragraph a border, and color it red, with the following markup:

<p style="border-style: groove; color: red;">                    
 Copyright 2006                    
</p>

When used in embedded or external style sheets, the first part of any style rule must determine the elements to which the rule will apply; we do this using a selector. In ASP.NET, we typically use two types of selectors:

1. element type selectors

An element type selector targets every single instance of the specified element. For example, if we wanted to change the colour of all level two headers in a document, we'd use an element type selector to target all <h2>s:

h2                    
{                    
 color: #369;                    
}

2. classes

Arguably the most popular way to use styles within your pages is to give each element a class attribute, then target elements that have a certain class value. For example, the following markup shows a paragraph whose class attribute is set to fineprint:

<p class="fineprint">                    
 Copyright 2006                    
</p>

Now, given that anything with the class fineprint should be displayed in, well, fine print, we can create a style rule that will reduce the size of the text in this paragraph, and any other element with the attribute class="fineprint":

.fineprint                    
{                    
 font-family: Arial;                    
 font-size: x-small;                    
}

Whether you're building external style sheets, embedded style sheets, or inline style rules, style declarations use the same syntax.

Now that you have a basic understanding of some of the fundamental concepts behind CSS, let's look at the different types of styles that can be used within our ASP.NET applications.

Style Properties

You can modify many different types of properties using style sheets. Here's a list of the most common property types:

  • font - This category provides you with the ability to format text level elements, including their font faces, sizes, decorations, weights, colors, etc.
  • background - This category allows you to customize backgrounds for objects and text. These values give you control over the background, including whether you'd like to use a color or an image for the background, and whether or not you want to repeat a background image.
  • block - This category allows you to modify the spacing between paragraphs, between lines of text, between words, and between letters.
  • box - The box category allows us to customize tables. If you need to modify borders, padding, spacing, and colors on a table, row, or cell, use the elements within this category.
  • border - This category lets you draw boxes of different colors, styles, and thicknesses around page elements.
  • list - This category allows you to customize the way ordered and unordered lists are created.
  • positioning - Modifying positioning allows you to move and position tags and controls freely.

These categories provide an outline of the aspects of a design that can typically be modified using CSS. As we progress through the book, the many types of style properties will become evident.

The CssClass Property

Once you've defined a class in a style sheet (be it external or internal), you'll want to begin to associate that class with elements in your Web Forms. You can associate classes with ASP.NET Web server controls using the CssClass property. In most cases, the value you give the CssClass property will be used as the value of the resulting element's class attribute.

Let's see an example. First, create in your Learning folder a file named Styles.css, and copy this code into it:

Example 4.28. Styles.css                    
                   
.title                    
{                    
 font-family: Arial, Helvetica, sans-serif;                    
 font-size: 19px                    
}                    
.dropdownmenu                    
{                    
 font-family: Arial;                    
 background-color: #0099FF;                    
}                    
.textbox                    
{                    
 font-family: Arial;                    
 background-color: #0099FF;                    
 border: 1px solid                    
}                    
.button                    
{                    
 font-family: Arial;                    
 background-color: #0099FF;                    
 border: 1px solid                    
}

Then, create a new file named UsingStyles.aspx with this code:

Example 4.29. UsingStyles.aspx (excerpt)                    
                   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                    
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                    
<html>                    
 <head>                    
   <title>Testing CSS</title>                    
   <link href="Styles.css" type="text/css" rel="stylesheet" />                    
 </head>                    
 <body>                    
   <form runat="server">                    
     <p class="title">Please select a product:</p>                    
     <p>                    
       <asp:DropDownList id="productsList"                    
           CssClass="dropdownmenu" runat="server">                    
         <asp:ListItem Text="Shirt" selected="true" />                    
         <asp:ListItem Text="Hat" />                    
         <asp:Listitem Text="Pants" />                    
         <asp:ListItem Text="Socks" />                    
       </asp:DropDownList>                    
     </p>                    
     <p>                          
       <asp:TextBox id="quantityTextBox" CssClass="textbox"                    
           runat="server" />                    
     </p>                    
     <p>                    
       <asp:Button id="addToCartButton" CssClass="button"                    
           Text="Add To Cart" runat="server"  />                    
     </p>                    
   </form>                    
 </body>                    
</html>

Loading this page should produce the output shown in Figure 4.13.

1556_0445_CSS
Figure 4.13. CSS at work

In the next chapter, we'll learn to use Visual Web Developer to create CSS definitions through a simple visual interface.

Summary

In this chapter, we discussed web forms, HTML server controls, web server controls, web user controls, master pages, and CSS. All these elements can be combined to create powerful structures for your web sites.

In the next chapter, we'll start building "real" web applications, putting into practice most of the theory you've learned so far, and using a professional development environment that will do part of the work for you.

Unfortunately, this is where our excerpt of Build Your Own ASP.NET Web Site Using VB and C# ends. Review the rest of the book's content, and don't forget to download these chapters in PDF format.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: