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.
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-
runat="server"
off the head control, but this will mean you cannot use server side controlsI 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With