tags:

views:

296

answers:

4

In a new ASP.NET site there is a ContentPlaceHolder for the title:

<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>

In the page:

<asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server">
    About Us
</asp:Content>

Why is this? Why can't the title property/attribute be used on the page directive?

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

Both methods have the same result. For me the ContentPlaceHolder approach seems hackish.

If you needed a dynamic title you can do it like this in the aspx page:

<%= this.Title = "About Me" %>
A: 

One possible explanation (although this isn't relevant for your simple example) - when you have script content in your <head> element you can't add runat="server" or access it through Page.Head. For instance (sorry this is off the top of my head):

<head>
<script type="text/javascript" src="<%= ResolveClientUrl("~/Scripts/script.js") %>"></script>
</head>

In that example using a ContentPlaceHolder would be one way of getting round not being able to access the head programmatically. Of course, you could probably also use <title><%= Page.Title %></title>, it depends on your preference (personally I'd be a bit torn).

roryf
A: 

You shouldn't be thinking of your views as gigantic objects that you interact with programmatically in MVC, they should be lightweight templates for generating html.

If you think about your views as templates rather then objects, using <ContentPlaceHolder /> is a heck of a lot less kludgy then using runat="server"

Matt Briggs
+2  A: 

See this post.

mxmissile
+1  A: 

If you used Title attribute of @Page directive instead you would have to set an application-wide title in each view duplicating code and violating single responsibility principle.

Alexander Prokofyev