258Microsoft Visual Studio 2010: A Beginner’s Guide

Organizing View Files

The file structure in Figure 9-2 shows that Views appear in the Views folder and have a *.aspx file extension. Each subfolder under the Views folder corresponds to a Controller, and the Views within the subfolder correspond generally to Controller actions. When

a Controller passes control to a View, by calling View, ASP.NET MVC searches for the View in the Views folder with the subfolder named the same as the Controller and the file named the same as the action calling the View.

Notice that there is a Shared folder. Sometimes, you’ll want to have a View that is shared by two or more Controller actions, and you can put these shared Views in the Shared subfolder. Whenever ASP.NET MVC doesn’t find a View in the Controller-named subfolder, it will search for the View in the Shared folder. An important file in the Shared subfolder is the MasterPage, which is discussed next.

Assigning MasterPage Files

Most sites on the Web have multiple pages, each with common elements. They all have the same header, menu, sidebars, and footers. When you first build a site, you can duplicate this common content with no trouble, but this copy-and-paste type duplication will cause a lot of headaches in the future. The first time you have to change the common elements, you’ll need to visit every page. If the site has only a few pages, no problem, but the reality is that most sites of any success grow to dozens or hundreds of pages. It is beyond practical to try to update every page on a site every time the common content changes.

This is where MasterPages help, allowing you to specify the common content in one place where you can have content pages that use the MasterPage. Whenever something changes in the common content, you update the MasterPage, and every page of a site that uses the MasterPage is automatically updated. Listing 9-3 shows the MasterPage, created by ASP.NET MVC, that the content page in Listing 9-2 uses.

Listing 9-3 A MasterPage

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

Page 281
Image 281
Microsoft 9GD00001 manual Organizing View Files, Assigning MasterPage Files, Listing 9-3 a MasterPage