Question

If i have an ASP.NET MVC 2 Web Application with the following Views:

  1. Main.aspx
  2. Page1.aspx
  3. Page2.aspx

And all Views inherit from a MasterView called Site.master,

I want to be able to have a default Title/H1 for the page, which can be overriden in the deriving Views.

E.g Main.aspx would have "MySite - xxx", Page1.aspx would have "MySite - Page 1", Page2.aspx would have "MySite - Page2".

And if i choose not to set the Title/H1 in a new derived view, the master Title/H1 would be displayed.

With WebForms, i would accomplish this in the following way:

  1. Make the Title/H1 tags on the master runat="server"
  2. Expose protected properties on the master code-behind
  3. On Page_Load of the derived pages code-behind, set the property (Master.Title = "Page 1").
  4. On Page_PreRender of the master code-behind, set the Title/H1 tags to "My Site - " + Title;

How can we accomplish this with ASP.NET MVC?

I could do this in the master:

<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>

And then set it in the view:

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    MySite - Page 1
</asp:Content>

But i wanted to be able to only specify "Page 1" in the View, and the title gets magically changed to "MySite - Page 1". Know what i mean? The "MySite - " part of the title needs to be the template for the title.

I'm probably missing something obvious here. :)

Was it helpful?

Solution

With a quick search I found this:

http://haacked.com/archive/2009/04/03/tipjar-title-tags-and-master-pages.aspx

explains why

<title>MySite<asp:content..../></title>

doesn't work

OTHER TIPS

This is how I usually do it:

<title>MySite - <%: Page.Title ?? "Default title" %></title>

in your MasterPage.

Then, you can define the Title property on a content page like this:

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

Edit:

Well, you might want to see this SO question: ASP.NET MVC - View with master page, how to set title?.

Is much easier as you are describing it.

Just add a content placeholder to your master page

<title>
    My Site - <asp:ContentPlaceHolder ID="PageTitle" runat="server" />
</title>

Then in your Content Page use it as

<asp:Content ID="Content3" ContentPlaceHolderID="PageTitle" runat="server">
    My Page
</asp:Content>

This way will work but you have to use an HTML HEAD tag, not a server control. So simply remove runat="server" from your HEAD.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top