Search code examples
c#asp.net-mvcmaster-pagespage-title

ASP.NET MVC - How To Design Dynamic H1/Title Scheme?


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. :)


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