Sunday, April 16, 2017

Partially defining an ASP.NET page's title in a ContentPlaceHolder

I've recently been working on an ASP.NET web site that has a bunch of pages using a master page as a template. For the sake of deduplication, I'd prefer to put the site's name inside the <title> tag in the master but also allow specific pages to specify their titles. I tried this:

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

Then in an individual page, I had this:

<asp:Content ID="Content1" ContentPlaceHolderID="title" Runat="Server">Neat Page</asp:Content>

The goal was to get "My Site - Neat Page" showing as the title for that page. Alas, I got only "Neat Page".

Strangely, ASP.NET isn't really a fan of loose text inside <title> when there's a server-side control there too. The solution is to wrap the literal text in, well, a literal:

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

Now each page gets the site name and its own name merged together.

No comments:

Post a Comment