NicolTIP#005: How to show the same content in two ore more positions using master page in ASP.NET

To write a web site and give to the entire site a coherent “look” with ASP.NET and master pages is very easy and productive. In brief, into the master page you need to put “placeholders” using the tag <asp:ContentPlaceHolder/> and into the content page, you can map real content with contenplaces (more information).

Sometime can be required to put the same content in more places, an example is the “title” field that you could put both in the header\title field and into a H1 tag into the body.

This means, starting from the following content page:

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Root.Master" AutoEventWireup="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Title" runat="server">This is my title</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MyContent" runat="server">This is my content</asp:Content>

To obtain the following html output:

<html>
<head>
<title>This is my title</title>
</head>
<body>
<h1>This is my title</h1>
This is my content
</body>
</html>

The easy way I found is shown in the following master page:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Root.master.cs" Inherits="NicolD.MasterPages.Root" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head runat="server">
<title><asp:ContentPlaceHolder id="Title" runat="server"></asp:ContentPlaceHolder></title>
</head>
<body>
<h1><span id="TitleOnPage" runat="server"></span></h1>
<asp:ContentPlaceHolder id="MyContent" runat="server" Visible="false"></asp:ContentPlaceHolder>
</body>
</html>

the true secret is in the master page’s code behind:-), where I filled “TitleOnPage” with “Title” place holder content.

public partial class Root : System.Web.UI.MasterPage
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);

        this.Page.LoadComplete += new EventHandler(Page_LoadComplete);
}

    private void Page_LoadComplete(object sender, EventArgs e)
{
        LiteralControl lc = (LiteralControl)Title.Controls[0];
TitleOnPage.InnerText = lc.Text;
}

}