Language

UI and Navigation

By |

In this tutorial, you will modify the UI of the default Web application to support features of the Wingtip Toys store front application. Also, you will add simple and data bound navigation. This tutorial builds on the previous tutorial “Create the Data Access Layer” and is part of the Wingtip Toys tutorial series.

What you'll learn:

  • How to change the UI to support features of the Wingtip Toys store front application.
  • How to configure an HTML5 element to include page navigation.
  • How to create a data-driven control to navigate to specific product data.
  • How to display data from a database created using Entity Framework Code First.

In this tutorial, you will modify the UI of the default Web application to support features of the Wingtip Toys store front application. Also, you will add simple and data bound navigation. This tutorial builds on the previous tutorial “Create the Data Access Layer” and is part of the Wingtip Toys tutorial series.

What you'll learn:

  • How to change the UI to support features of the Wingtip Toys store front application.
  • How to configure an HTML5 element to include page navigation.
  • How to create a data-driven control to navigate to specific product data.
  • How to display data from a database created using Entity Framework Code First.

ASP.NET Web Forms allow you to create dynamic content for your Web application. Each ASP.NET Web page is created in a manner similar to a static HTML Web page (a page that does not include server-based processing), but ASP.NET Web page includes extra elements that ASP.NET recognizes and processes to generate HTML when the page runs.

With a static HTML page (.htm or .html file), the server fulfills a Web request by reading the file and sending it as-is to the browser. In contrast, when someone requests an ASP.NET Web page (.aspx file), the page runs as a program on the Web server. While the page is running, it can perform any task that your Web site requires, including calculating values, reading or writing database information, or calling other programs. As its output, the page dynamically produces markup (such as elements in HTML) and sends this dynamic output to the browser.

Modifying the UI

You’ll continue this tutorial series by modifying the Default.aspx page. You will modify the UI that’s already established by the default template used to create the application. The type of modifications you’ll do are typical when creating any Web Forms application. You’ll do this by changing the title, replacing some content, and removing unneeded default content.

  1. Open or switch to the Default.aspx page.
  2.  If the page appears in Design view, switch to Source view.
  3.  At the top of the page in the @Page directive, change the Title attribute to “Welcome”, as shown below.
    	<%@ Page Title="Welcome" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" 
                     CodeBehind="Default.aspx.cs" Inherits="WingtipToys._Default" %>
    
  4. Replace default content so that the markup appears as below.
    <asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
        <section class="featured">
            <div class="content-wrapper">
                <hgroup class="title">
                    <h1><%: Title %>.</h1>
                    <h2>Wingtip Toys can help you find the perfect gift</h2>
                </hgroup>
                <p>
                    We're all about transportation toys. You can order 
                    any of our toys today. Each toy listing has detailed 
                    information to help you choose the right toy.
                </p>
            </div>
        </section>
    </asp:Content>
    
  5. Replace all the content contained in the MainContent placeholder , so that this HTML section will now be the following:
    <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
        <section style="vertical-align: middle">
        </section>
    </asp:Content>
  6. Save the Default.aspx page by selecting Save Default.aspx from the File menu.

The resulting Default.aspx page will appear as follows:

<%@ Page Title="Home" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WingtipToys._Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1><%: Title %>.</h1>
                <h2>Wingtip Toys can help you find the perfect gift</h2>
            </hgroup>
            <p>
                We're all about transportation toys. You can order 
                any of our toys today. Each toy listing has detailed 
                information to help you choose the right toy.
            </p>
        </div>
    </section>
</asp:Content>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <section style="alignment-adjust: middle">
    </section>
</asp:Content> 

In the example, you have set the Title attribute of the @Page directive. When the HTML is displayed in a browser, the server code <%: Page.Title %> resolves to the content contained in the Title attribute.

The example page includes the basic elements that constitute an ASP.NET Web page. The page contains static text as you might have in an HTML page, along with elements that are specific to ASP.NET.

@Page Directive

ASP.NET Web Forms usually contain directives that allow you to specify page properties and configuration information for the page. The directives are used by ASP.NET as instructions for how to process the page, but they are not rendered as part of the markup that is sent to the browser.

The most commonly used directive is the @Page directive, which allows you to specify many configuration options for the page, including the following:

  • The server programming language for code in the page, such as C#.
  • Whether the page is a page with server code directly in the page, which is called a single-file page, or whether it is a page with code in a separate class file, which is called a code-behind page.
  • Whether the page has an associated master page and should therefore be treated as a content page.
  • Debugging and tracing options.

If you do not include an @Page directive in the page, or if the directive does not include a specific setting, a setting will be inherited from the Web.config configuration file or from the Machine.config configuration file. The Machine.config file provides additional configuration settings to all applications running on a machine.

Web Server Controls

In most ASP.NET Web Forms applications, you will add controls that allow the user to interact with the page, including buttons, text boxes, lists, and so on. These Web server controls are similar to HTML buttons and input elements. However, they are processed on the server, allowing you to use server code to set their properties. These controls also raise events that you can handle in server code.

Server controls use a special syntax that ASP.NET recognizes when the page runs. The tag name for ASP.NET server controls starts with an asp: prefix. This allows ASP.NET to recognize and process these server controls. The prefix might be different if the control is not part of the .NET Framework. In addition to the asp: prefix, ASP.NET server controls also include the runat="server" attribute and an ID that you can use to reference the control in server code.

When the page runs, ASP.NET identifies the server controls and runs the code that is associated with those controls. Many controls render some HTML or other markup into the page when it is displayed in a browser.

Server Code

Most ASP.NET Web Forms applications include code that runs on the server when the page is processed. As mentioned above, server code can be used to do a variety of things, such as adding data to a ListView control. ASP.NET supports many languages to run on the server, including C#, Visual Basic, J#, and others.

ASP.NET supports two models for writing server code for a Web page. In the single-file model, the code for the page is in a script element where the opening tag includes the runat="server" attribute. Alternatively, you can create the code for the page in a separate class file, which is referred to as the code-behind model. In this case, the ASP.NET Web Forms page generally contains no server code. Instead, the @Page directive includes information that links the .aspx page with its associated code-behind file.

The CodeBehind attribute contained in the @Page directive specifies the name of the separate class file, and the Inherits attribute specifies the name of the class within the code-behind file that corresponds to the page.

Updating the Master Page

In ASP.NET Web Forms, master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display, as explained above. When users request the content pages, ASP.NET merges them with the master page to produce output that combines the layout of the master page with the content from the content page.

The new site needs a single logo to display on every page. To do this, you can modify the HTML on the master page.

  1. In Solution Explorer, find and open the Site.Master page.
  2. If the page is in Design view, switch to Source view.
  3. Update the master page by replacing the existing <title> element with the following markup:
            <title><%: Page.Title %> - Wingtip Toys</title>
  4. Update the master page again by replacing the existing <header> element with the following markup:
    <header>
        <div class="content-wrapper">
            <div class="float-left">
                <p class="site-title">
                    <a id="A2" runat="server" href="~/">
                    <asp:Image  ID="Logo" runat="server" ImageUrl="~/images/logo.jpg" 
                        BorderStyle="None" />
                    </a>
                </p>
            </div>
            <div class="float-right">
                <section id="login">
                    <asp:LoginView runat="server" ViewStateMode="Disabled">
                        <AnonymousTemplate>
                            <ul>
                                <li><a runat="server" href="~/Account/Register.aspx">Register</a></li>
                                <li><a runat="server" href="~/Account/Login.aspx">Log in</a></li>
                            </ul>
                        </AnonymousTemplate>
                        <LoggedInTemplate>
                            <p>
                                Hello, <a runat="server" class="username" href="~/Account/ChangePassword.aspx" title="Change password">
                                <asp:LoginName runat="server" CssClass="username" /></a>!
                                <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" />
                            </p>
                        </LoggedInTemplate>
                    </asp:LoginView>
                </section>
                <nav>
                    <ul id="menu">
                        <li><a runat="server" href="~/">Home</a></li>
                        <li><a runat="server" href="~/About.aspx">About</a></li>
                        <li><a runat="server" href="~/Contact.aspx">Contact</a></li>
                    </ul>
                </nav>
            </div>
        </div>
    </header>

This HTML will display the image named logo.jpg from the root of the Web application which you’ll add later. When a page that uses the master page is displayed in a browser, the logo will be displayed. If a user clicks on the logo, the user will navigate back to the Default.aspx page. The HTML anchor tag <a> wraps the image server control and allows the image to be included as part of the link. The href attribute for the anchor tag specifies the root "~/" of the Web site as the link location. By default, the Default.aspx page is displayed when the user navigates to the root of the Web site. The Image <asp:Image> server control includes addition properties, such as BorderStyle, that render as HTML when displayed in a browser.

Master Pages

A master page is an ASP.NET file with the extension .master (for example, Site.Master) with a predefined layout that can include static text, HTML elements, and server controls. The master page is identified by a special @Master directive that replaces the @Page directive that is used for ordinary .aspx pages.

In addition to the @Master directive, the master page also contains all of the top-level HTML elements for a page, such as html, head, and form. For example, on the master page you added above, you use an HTML table for the layout, an img element for the company logo, static text, and server controls to handle common membership for your site. You can use any HTML and any ASP.NET elements as part of your master page.

In addition to static text and controls that will appear on all pages, the master page also includes one or more ContentPlaceHolder controls. These placeholder controls define regions where replaceable content will appear. In turn, the replaceable content is defined in content pages, such as Default.aspx, using the Content server control.

Adding Image Files

The logo image that is referenced above, along with all the product images, must be added to the Web application so that they can be seen when the project is displayed in a browser.

Download from MSDN Samples site:

Getting Started with ASP.NET Web Forms 4.5

The download includes resources in the WingtipToys-Assets folder that are used to create the sample application.

  1. If you haven’t already done so, download the compressed sample files using the above link from the MSDN Samples site.
  2. Once downloaded, open the .zip file and copy the contents to a local folder on your machine.
  3. Find and open the WingtipToys-Assets folder.
  4. By dragging and dropping, copy the Catalog folder from your local folder to the root of the Web application project in the Solution Explorer of Visual Studio.

    Copy Image Files to the Project

  5. Next, copy the logo.jpg file from the WingtipToys-Assets folder to the Images folder of the Web application project in the Solution Explorer of Visual Studio.
  6. Click the Show All Files option at the top of the Solution Explorer to update the list of files if you don’t see the new files.

    Solution Explorer now shows the updated project files.

    Solution Explorer

Adding Pages

Before adding navigation to the Web application, you’ll first add the new pages that you’ll navigate to. Later in this tutorial series, you’ll display products and product details on these new pages.

  1. In Solution Explorer, right-click WingtipToys, click Add, and then click New Item.
    The Add New Item dialog box is displayed.

  2. Select the Visual C# > Web templates group on the left. Then, select Web Form using Master Page from the middle list and name it ProductList.aspx.

    Add New Item Dialog Box

  3. Select Site.Master to attach the master page to the newly created .aspx page.

    Select a Master Page Dialog Box

  4. Add an additional page named ProductDetails.aspx by following these same steps.

Updating the StyleSheet

The default project template includes a cascading style sheet (CSS) file named Site.css. This file contains style rules that are applied to elements in the Web pages of the site. CSS styles define how elements are displayed and where they are positioned on the page. CSS styles can be placed inline within a single HTML element, grouped in a style block within the head section of a Web page, or imported from a separate style sheet.

In this tutorial you will comment out two styles to change the look of the Web site.

  1. In Solution Explorer, find the Content folder and open the Site.css file.
  2. Find the .content-wrapper style and set the max-width value to 1060px.
  3. Find the .main-content style and the .featured + .main-content style and comment out the lines that it contains by selecting the lines and clicking the comment out icon on the tool bar.
  4. The style updates will appear as shown below:

    Style Changes

  5. Next, find the table section of the stylesheet and comment out the border related table styles as follows:
     
    Additional Style Changes

Modifying the Default Navigation

The default navigation for every page in the application can be modified by changing the nav element that's in the Site.Master page.

  1. In Solution Explorer, locate and open the Site.Master page.
  2. Find the nav element and replace it with the nav element shown below:
                <nav>
                    <ul id="menu">
                        <li><a href="/">Home</a></li>
                        <li><a href="/About.aspx">About</a></li>
                        <li><a href="/Contact.aspx">Contact</a></li>
                        <li><a href="/ProductList.aspx">Products</a></li>
                    </ul>
                </nav>

The nav element is new with HTML5. It makes adding and displaying navigation easy. As you can see in the above HTML, you modified each line item <li> containing an anchor tag <a> with a link href attribute. Each href points to a page in the Web application. In the browser, when a user clicks on one of these links (such as Products), they will navigate to the page contained in the href(such as ProductList.aspx).

Adding a Data Control to Display Navigation Data

Next, you’ll add a control to display all of the categories from the database. Each category will act as a link to the ProductList.aspx page. When a user clicks on a category link in the browser, they will navigate to the products page and see only the products associated with the selected category.

You’ll use a ListView control to display all the categories contained in the database.  To add a ListView control to the master page:

1. In the Site.Master page, update the <div> element containing the id="body" attribute by adding the following markup:

            <div id="body">
                <section style="text-align: center; background-color: #fff">
                    <asp:ListView ID="categoryList"  
                        ItemType="WingtipToys.Models.Category" 
                        runat="server"
                        SelectMethod="GetCategories" >
                        <ItemTemplate>
                            <b style="font-size: large; font-style: normal">
                            <a href="/ProductList.aspx?id=<%#: Item.CategoryID %>">
                            <%#: Item.CategoryName %>
                            </a>
                            </b>
                        </ItemTemplate>
                        <ItemSeparatorTemplate> - </ItemSeparatorTemplate>
                    </asp:ListView>
                </section> 

                <asp:ContentPlaceHolder runat="server" ID="FeaturedContent" />
                <section class="content-wrapper main-content clear-fix">
                    <asp:ContentPlaceHolder runat="server" ID="MainContent" />
                </section>
            </div>

This code will display all the categories from the database. The ListView control displays each category name as link text and includes a link to the ProductList.aspx page with a query-string value containing the ID of the category. By setting the ItemType property in the ListView control, the data-binding expression Item is available within the ItemTemplate node and the control becomes strongly typed. You can select details of the Item object using IntelliSense, such as specifying the CategoryName. This code is contained inside the container <%#: %> that marks a data-binding expression. By adding the (:) to the end of the <%# prefix, the result of the data-binding expression is HTML-encoded. When the result is HTML-encoded, your application is better protected against cross-site script injection (XSS) and HTML injection attacks.

Note   When you add code by typing during development, you can be certain that a valid member of an object is found because strongly typed data controls show the available members based on IntelliSense. IntelliSense offers context-appropriate code choices as you type code, such as properties, methods, and objects.

Linking the Data Control to the Database

Before you can display data in the data control, you need to link the data control to the database. To make the link, you can modify the code behind of the Site.Master.cs file.

  1. In Solution Explorer, right-click the Site.Master page and then click View Code. The Site.Master.cs file is opened in the editor.
  2. At the beginning of the Site.Master.cs file update the included an additional namespace so that the namespaces appear as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using WingtipToys.Models;
    		
  3. Add the GetCategories method directly after the Page_Load event handler as follows:
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
            
            public IQueryable<Category> GetCategories()
            {
                var db = new WingtipToys.Models.ProductContext();
                IQueryable<Category> query = db.Categories;
                return query;
            }
    

The above code is executed when any page that uses the master page is loaded in the browser. The ListView control (named "categoryList") that you added earlier in this tutorial uses model binding to select data. In the markup of the ListView control you set the control's SelectMethod property to the GetCategories method, shown above. The ListView control calls the GetCategories method at the appropriate time in the page life cycle and automatically binds the returned data. You will learn more about binding data in the next tutorial.

Running the Application and Creating the Database

Earlier in this tutorial series you created an initializer class (named "ProductDatabaseInitializer") and specified this class in the global.asax.cs file. The Entity Framework will generate the database when the application is run the first time because the Application_Start method contained in the global.asax.cs file will call the initializer class. The initializer class will use the model classes (Category and Product) that you added earlier in this tutorial series to create the database.

  1. In Visual Studio press Ctrl+F5.

    Viewing the Application in a Browser

    When the application is run, the application will be compiled and the database named wingtiptoys.mdf will be created. It will take a little time to set everything up first this first run. In the browser, you will see a category navigation menu. This menu was generated by retrieving the categories from the database. The navigation menu also uses the <nav> HTML5 element that you modify earlier.

  2. Close the browser.

Reviewing the Database

Open the Web.config file and look at the connection string section. You can see that the AttachDbFilename value in the connection string points to the DataDirectory for the Web application project. The value |DataDirectory| is a reserved value that represents the App_Data folder in the project. This folder is where the database is located.

  <connectionStrings>
    <add name="DefaultConnection" 
         connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WingtipToys-20120302100502;Integrated Security=True" 
         providerName="System.Data.SqlClient" />
    <add name="WingtipToys" 
         connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\wingtiptoys.mdf;Integrated Security=True" 
         providerName="System.Data.SqlClient " />
  </connectionStrings>

Note   If the App_Data folder is not visible or if the folder is empty, select the Show All Files icon and the Refresh icon at the top of the Solution Explorer window. Expanding the width of the Solution Explorer windows may be required to show all available icons.

Now you can inspect the data contained in the wingtiptoys.mdf database file by using the Database Explorer window (Server Explorer window in Visual Studio).

  1. Expand the App_Data folder.
  2. Right-click the wingtiptoys.mdf database file and select Open.
    Database Explorer is displayed.

    Database Explorer

  3. Expand the Tables folder.
  4. Right-click the Products table and select Show Table Data.
    The Products table is displayed.

    Products Table

    This view lets you see and modify the data in the Products table by hand.

  5. Close the Products table window.
  6. In the Database Explorer, right-click the Products table and select Open Table Definition.
    The data design for the Products table is displayed.

    Products Table Data Design

    Here you see the SQL DDL statement that was used to create the table. You can also use the UI to modify the schema.
  7. In the Database Explorer, right-click wingtiptoys.mdf and select Close Connection.
    By detaching the database from Visual Studio, the database schema will be able to be modified later in this tutorial series.
  8. Close the Database Explorer.

Summary

In this tutorial of the series you have added some basic UI, graphics, pages, and navigation. Additionally, you ran the Web application, which created the database from the data classes that you added in the previous tutorial. You also viewed the contents of the Products table of the database. In the following tutorial, you'll display data items and details from the database.

Additional Resources

Introduction to Programming ASP.NET Web Pages
ASP.NET Web Server Controls Overview
CSS Tutorial
Erik Reitan

By Erik Reitan, Erik Reitan is a Senior Programming Writer at Microsoft. During his spare time he enjoys developing Windows Phone and Windows 8 apps. Follow him on Twitter at @ReitanErik.