Chapter 9: Creating Web Applications with ASP.NET MVC

261

A good example of where a Partial View is useful is illustrated in the code produced by the ASP.NET MVC Project Wizard, where it created the LogonUserControl.ascx. The terms Partial View and User Control are synonymous, where the term User Control is familiar to developers who have worked with previous versions of ASP.NET Web Forms. Partial View is consistent with the ASP.NET MVC perspective of Views, where a Partial View is not an entire View, but a chunk of View content that can be reused with multiple Views. It isn’t coincidence that this control is physically located in the Views Shared folder, considering that it can be used on multiple pages. Remember, if ASP.NET MVC can’t find a file in a View folder named after a Controller, it will look in the Shared folder. Listing 9-4 shows the contents of LogonUserControl.ascx.

Listing 9-4 Contents of a Partial View

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<%

if (Request.IsAuthenticated) {

%>

Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!

[<%= Html.ActionLink("Log Off", "LogOff", "Account") %> ]

<%

}

else {

%>

[ <%= Html.ActionLink("Log On", "LogOn", "Account") %> ] <%

}

%>

The Control directive at the top of Listing 9-4 indicates that this is a Partial View. Within the control, you can see an if statement, where the language syntax is surrounded by <% and %> binding symbols. The additional syntax to separate code from markup might take a little getting used to, but it is typical in an MVC application to control how markup is rendered. The IsAuthenticated property of the Request object tells whether the current user is logged in, and the logic ensures the appropriate message displays. The ActionLink Html helper methods generate action tags with a URL for actions on the Account Controller. We’ve barely touched on routing and how a URL matches controllers and actions, but the next section explains how routes work in greater depth.

Page 284
Image 284
Microsoft 9GD00001 manual 261, Listing 9-4 Contents of a Partial View