Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate title tags using ASP.NET MasterPage

I need to set the title of a page dynamically, and so I use code similar to the following:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="~/about.aspx.cs" Inherits="Default" %>
<%@ Register Assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>
<%@ MasterType VirtualPath="MasterPage.master" %>
<%@ OutputCache Duration="43200" VaryByParam="*" Location="Server" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
 <title><%=pageTitle%></title>
</asp:Content>

But this generates duplicate title tags. Is there any way I can get around this? Thanks.

EDIT: Following from the suggestions below, I now have the following in my MasterPage:

<head id="Head1" runat="server">
<title>Default Title</title>
...
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head> 

and the following in my primary page:

    this.Title="xxx";

but I'm not getting any title (neither "Default Title" nor "xxx").

EDIT: Nevermind. Got it working using that method.

like image 488
alpheus Avatar asked Jan 20 '10 15:01

alpheus


1 Answers

If the second title tag was empty and at the end of the head tag, then what is happening is that the Head control (note the runat="server") cannot see a Title control within it's controls, and therefore adds an empty Title tag to the end.

Most of the answers here are valid, but for minimal change what you could do is add the following to your head control-

<title id="Title1" visible="false" runat="server"><%-- hack to turn the auto title off --%></title>

Other options include-

  • Take the runat="server" off the head control, but this will mean you cannot use server side controls
  • Use a Title control and set it programatically, like your solution.

I like the hidden title tag, because it allows you to use the ContentPlaceholder approach, which keeps it in the template. It also allows you to use a custom control to get the title (in our case, we're using a 3rd party library to pull the title from a DB)

See this blog post by Phil Haack for the background on this.

like image 151
Spongeboy Avatar answered Oct 06 '22 13:10

Spongeboy