Chapter 9: Creating Web Applications with ASP.NET MVC

257

Listing 9-2 A View’s HTML

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">

Home Page </asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

<h2><%= Html.Encode(ViewData["Message"]) %></h2> <p>

To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc"

title="ASP.NET MVC Website"> http://asp.net/mvc

</a>.

</p>

</asp:Content>

A quick overview of Listing 9-2 shows that there is a Page directive with a couple of Content containers. The Page directive specifies a MasterPage and Inherits attributes.

A MasterPage is a separate file that holds common HTML that can be shown on all pages of a site. You’ll see how the MasterPage works soon, but let’s stay focused on the current file in Listing 9-2 until then. ASP.NET MVC will compile this HTML into code behind the scenes, and the generated code will derive from the class defined by the Inherits attribute. The first Content container can hold metadata that goes into an HTML header. The

second Content container has the information that will display on the screen. Notice the Html.Encode(ViewData["Message"]) inside of binding tags <%= and %>. Any time you add code or need to access ViewData that was passed by the Controller, you will use the binding tags. Encode is one of several helper methods of the Html class, more of which you’ll see soon. The purpose of Encode is to translate HTML tags into their encoded representations for security purposes, ensuring that you don’t show any harmful JavaScript, or other markup that could possibly execute, to the user. ViewData["Message"] should be familiar, as it was set in the Index action in Listing 9-2 but is now being read and displayed on the screen by this View.

Page 280
Image 280
Microsoft 9GD00001 manual 257, Listing 9-2 a View’s Html