New book: Introducing Microsoft WebMatrix

We're very pleased to announce that Laurence Moroney's new book Introducing Microsoft WebMatrix (352 pages, Print ISBN: 978-0-7356-4970-5) is now available!

WebMatrix is a free web development stack that includes everything developers need to build modern web sites, including powerful text editors, a full-featured IIS 7-compatible web server, database development and query tools, PHP, AJAX, and JavaScript compatibility, seamless one-click deployment, search engine optimization, debugging support, and built-in traffic analysis. WebMatrix also includes the brand-new and exciting Microsoft ASP.NET Web Pages Framework. This is a very simple, very light, but extremely powerful framework that allows you to build fully functional, data-driven websites, more quickly and easily than ever before. And when you want to take the next step and build massively scalable websites, the syntax (nicknamed "Razor") is part of the ASP.NET MVC 3 release, so you'll be able to reuse your code and skills there.

The book is available through retailers now. Download an excerpt from the book: Chapter 10, " Building a Simple Web Application: Styles, Layout, and Templates."

Chapter 10

Building a Simple Web Application: Styles, Layout, and Templates

In this chapter, you will

Create and style a website.

Add style to your site by using CSS.

Use layout and templates.

In the previous chapters, you have been exploring some of the technologies available in Microsoft WebMatrix. Now, over the next few chapters, you’ll put the knowledge you’ve gained into practice by building a real site. The site you’ll build is a data-driven site with standard CRUD (Create, Read, Update, Delete) functionality for your users.

You’ll start with the basics, by creating a page in HTML that generates a simple to-do list. This will be a static HTML page that will give you some experience in exploring the styling capabilities of cascading style sheets (CSS). You’ll also see how to use the WebMatrix layout and template concepts to turn this page into a template for creating other pages. In Chapter 11, “Building a Simple Web Application: Using Data,” you’ll ”activate” the site by making it data driven rather than static, and then you’ll use the layout and templates from this chapter to create multiple webpages for your site.

Creating and Styling Your Site

In this section, you will create a new site and style it with CSS.

1. Start with an empty site by choosing Site From Template on the WebMatrix opening screen and then selecting the Empty Site template. Name the new template Ch10, as shown in Figure 10-1.

Switch to the Files workspace, create a new file, and name the file todo.cshtml.

Change the contents of this file to look like the following.

Figure 10-2 A simple HTML list.

In HTML, you can logically divide your page up into blocks by using the <div> tag. This is especially useful when you start looking at styling later in this chapter, where you can specify the style for a certain part of a page by styling its div.

4. The first thing to do is to wrap the list containing the to-do items into its own <div> as shown in the following code.

You can see from the preceding code that the <ul><li> list containing the items is now contained within the <div> tag. If you view the page now, it will look no different than it did earlier, because the <div> tag is a logical divider. It doesn’t have any physical appearance.

Getting Your Page Ready for CSS

You’re already familiar with those clickable areas on a page that link to another page. Although the term for these is hyperlinks, in HTML they were originally called anchors, so whenever you want to create one in HTML you use the anchor (<a>) tag.

The <a> tag works by making the content between the opening <a> tag and its matching closing </a> tag clickable. When the user clicks the enclosed content, the browser will be redirected to an HREF (hypertext reference) indicated by the href attribute within the <a> tag.

The href doesn’t have to be a website, as in the example in the preceding Note; it can also be something such as a JavaScript function that executes some code on the client side—that is, within the browser. There’s a special href that can be used as a placeholder while you’re developing your site, so that you can test that your hyperlink styles are working. To do this, use the number sign (#) character as your href. We’ll use this href in the following exercise.

1. To turn all the <li> items containing the to-do items into hyperlinks, simply wrap the text of the item in an <a> tag and set the href attribute to #, as shown in the following code.

Run the page. You’ll see that the elements on your list use a familiar style for hyperlinks: namely, a blue underline (see Figure 10-3).

The next thing to do is add a header and footer to the page. Add those by using the new <header> and <footer> tags available in HTML5, as shown in the following code.

As you can see, these are simply straightforward pieces of HTML. For the header, you just wrapped the <h1> tag that you created earlier in a <header> tag. For the footer, you just needed to create a little text and a hyperlink.

When you look at the page within the browser, it will now look something like that shown in Figure 10-4.

Other than the footer, it’s not much different, but don’t worry, that will soon change!

Adding Some Style with CSS

In the previous section, you created an HTML page and tweaked its content a little to add headers and footers. You also changed the list items in a <ul><li> list to make them hyper-links. All that was done both to make styling the list a little easier and to make it prettier than the default HTML. For example, because you made the list items into hyperlinks, the browser will provide rollover functionality, and you can style that functionality to improve the list’s appearance as the users roll over items. In this section, you’ll take a quick tour of CSS to see how you can use this technology on your to-do list.

As you might expect, you can use attributes to specify how any page element looks, changing characteristics such as font style, font size, colors, borders, and much more.

For example, you could change the font and color of the <h1> element defined on the example page like the following.

As you can see, the style attribute of the <h1> tag contains a list of properties that control the rendering style. The preceding markup sets the color to blue, the font size to 32, the font family to Verdana, and the text decoration to underline, giving you a result like what is shown in Figure 10-5.

FIguRE 10-5 Changing the style of the title.

Although using attributes directly within tags for styling (a technique called inline markup) works just fine, it isn’t the best way to style the page. Consider what would happen if you had to style every element that way. You’d end up with a lot of styling text on your pages, which would slow down both the download and the browser.

Fortunately, there is another way, and that is to use a style sheet on your page. Style sheets in HTML are called cascading style sheets (CSS), in which a style that is set on an element can be inherited by a child of the element. So, for example, if you put a style on a <div> and that <div> has child <ul> and <li> elements, then that style will also apply to them—unless you override that inherited style with a more specific style.

With that in mind, here’s what it takes to define the style on the <h1> tag in this chapter’s example, without using a lot of inline markup for the style attribute.

1. First, rather than putting all the styling markup into the <h1> tag itself, just specify its class attribute, as shown in the following code.

<h1 class="Title">My honeydo todo list</h1>

2. Now that the tag has a class, you can tell the browser to use a specific style for everything that has this class. In CSS code syntax, you do that using the following.

The CSS style “language” consists of a list of properties separated by semicolons and contained within curly braces ({...}). If you want the style thus defined to apply to a class, you define the class name by using the “dot” syntax, which is nothing more than the class name preceded by a dot.

Place this code within a <style> tag in the header of the page. The complete page markup should now look like the following.

Remember that the <h1> had a class of Title, so by setting the .Title, you can set the style for every element that has the same class.

4. When you want to set the style for a specific element, you can either use a class for that element, knowing that there’s only one instance of that class, or you can name the element by using an ID, and then set the class for that ID. Take a look at your HTML; you’ll notice that the list of items is contained within a <div> that has been given the ID todolist. You can set the style for this ID by preceding its name with a number sign (#) in your style sheet definition. Add the following lines to the style sheet definition, like this:

#todolist{ font-family: Geneva, Tahoma, sans-serif; }

This defines a style for the todolist <div>, and because style sheets cascade, any element within this div will also have this style applied to it. So even though you haven’t explicitly set a style for the <li> elements containing the text, the todolist style will still be applied.

5. Remember that the browser defaults to rendering <li> objects in a <ul> list as bulleted items. You can override that by setting the style. Because these objects are inside the div named todolist, you can address them easily to change their style.

Update your style sheet definition so that it looks like the following.

#todolist{

font-family: Geneva, Tahoma, sans-serif;

}

#todolist ul{

list-style: none; margin: 0; padding: 0; border: none;

}

This simply states that for each <ul> within #todolist, set the list style to be none (no bullets), no margin (0), no padding (0), and no border (none).

The result, as you can see in Figure 10-7, is that the bullets are now gone.

6. The text of each list item was held within an <a> tag, so you can also use CSS to define the appearance of every <a> tag within every <li> tag within todolist. Add this to do that now.

The settings here pretty much speak for themselves. Figure 10-8 shows what the page looks like when you run it now.

7. The <a> tag provides another behavior when users point to the link with the mouse. You can use this feature to “hot track” the mouse and change the style of the element when the mouse pointer is over it. CSS also supports this, using the following syntax.

#todolist li a:hover{}

Define what to do when the mouse pointer is over an anchor tag by adding the following code.

Using CSS Files

It’s fun to experiment with CSS—and WebMatrix makes it easy. As you’ve been working through these exercises, you probably thought, “Wait a minute—this CSS stuff is all very nice, but what if my site has more than one page?”

That’s a great question. In our example, the CSS has been integrated into the page <head> by using a <style> block. The good news is that a webpage doesn’t have to use a <style> block to use CSS—it can point to an external CSS file by using a <link> tag instead. That way, any page that points to that file will be able to take advantage of the same styles.

It’s easy to do this with WebMatrix.

With the Files workspace open, click the New button and select New File. The New Files dialog box opens.

Select CSS as the file type, and give the file the name todo.css. Click OK, and WebMatrix will create the CSS file for you.

The file will contain an empty <body> tag, like the following.

body { }

Replace this with the following CSS. I’ve tidied up some of the CSS that you created as you worked along through this chapter, and I have created specific CSS styles for the header instead of using the class attribute on the <h1> tag, which produces cleaner HTML on your page, as you’ll see in a moment.

This CSS centers the footer text and assigns it a small font in a gray color, as well as a border that separates it from the rest of the list. You can see the results in Figure 10-10.

Figure 10-10 The fully styled list.

At this point, you have a basic static HTML page that has been styled as you would like the final site to look. Now I’ll switch gears and show you how you can turn this page into a template for all the pages that the to-do list website uses, so that you don’t have to write out the styles and content for every page.

using Layout Pages and Templates

Imagine for a moment that your site has several pages like the page that you have right now, which lists your to-do items, but that you would like to have other pages for creating an item, deleting an item, or editing an item on your to-do list. Each of these pages would use the same header (“My honeydo to-do list”) and footer (“Built by me”) as the page you’ve just created; only the part of the page that’s between the header and footer will be different.

In this section, you’ll see how to create a layout page that contains the header and footer, and you’ll learn how to edit your existing page to get it to use that layout page as its template.

Using RenderBody()

The key to the Razor view engine is the RenderBody() command. With this command, you can tell a template page to render the contents of your desired page at a specific location in the template. Don’t worry if this is a little confusing! It’s best understood by example.

Look at your existing todo.cshtml page. The only distinctive content in the page is the div containing the list.

The rest of the markup and code is simply HTML “plumbing” plus the header and footer. This illustrates an important concept: When you want to create a template, it’s best to make the template do the “plumbing,” and have it render any distinctive content at a particular location. In other words, a template that renders the to-do list would contain the HTML header, the page header, and the footer within it, and would use the RenderBody() command to display the page body (the <div> containing the to-do list, in this case). The following shows what such a template would look like.

Note that everything you had on your todo.cshtml page is here except the <div> that contains the distinctive content. In place of that content, you now have a RenderBody command that, when the template is complete, will render the distinctive content for you.

Create a new file named _sitelayout.cshtml and copy the preceding code into it.

Then go back to todo.cshtml and delete everything except the <div> containing the to-do list, so that it looks like the listing you saw earlier.

3. Finally, you’ll need to create another page, named _PageStart.cshtml, which is a special page that WebMatrix always calls when rendering a page. You can use this page to tell the system what the layout for any page is. The entire content of this page should use the following code.

@{ Layout = "~/_sitelayout.cshtml"; }

With all that in place, here’s what happens when you now visit todo.cshtml. WebMatrix will look and see that there’s a layout template for the page (_sitelayout.cshtml). It will then render that page (and not todo.cshtml), which causes the RenderBody() command to be called. This command then renders the contents of todo.cshtml, providing the <div>.

4. Run the page. You’ll see something like Figure 10-11.

Of course, the page doesn’t look any different than it did before. That’s because the layout page that acts as the template uses the same code as the earlier todo.cshtml did. But what’s nice now is that all the parts of the content are externalized so that you can reuse them easily.

5. As an example, create another page called about.cshtml, and give it just the following content.

You don’t need any <html>, <head>, or <body> tags or anything—just the two preceding lines of code.

6. Run this page now, and you’ll see something like Figure 10-12.

As you can see, you have created and styled a page, and then created a layout page that can be used as a template for all the pages on your site.

In Chapter 11, you’ll add a database to this site and use the template page to create the rest of the pages, giving you a fully active to-do list.

Summary

This chapter walked through the first steps of using WebMatrix to put a site together end to end. To start the site, you created a webpage that rendered static HTML. You then saw how to use CSS to style the HTML and make it more attractive. You externalized the CSS to make that reusable. Then you used a layout page and template to turn the HTML into a template that you can easily reuse across many pages. The template contains the HTML common to all pages and uses the RenderBody command to render distinctive content for each page.

In the next chapter you’ll build on these techniques, adding a database to create an active site that retrieves data from that database and uses the data to build dynamic pages for creating to-do items. Eventually, you’ll be able to add, update, and delete items from the to-do list as well as render the list as you did in this chapter.