Getting the PageTitle
Getting the PageTitle of a page should be just a property away would you think. I would call Page.Title to get the title of the current page.
Unfortunately Page.Title contains “\r\n ” and the title of the page is in a new line, like this:
<title> RH Test </title>
The property will only return the first row, which is not very helpful 🙁
So what can we do? Since the title is set through a control within a ContentPlacehoder, my way was to get the control and take the value from it. And… it worked. An extension method will traverse all controls, to find the desired one.
public string GetPageTitle()
{
var literal = Page.Header.FindControlsOfType<ContentPlaceHolder>().Single(p => p.ID == "PlaceHolderPageTitle").FindControlsOfType<EncodedLiteral>().FirstOrDefault();
if (literal != null)
{
string pageTitle = literal.Text;
return pageTitle;
}
return null;
}
// and an extension method (need to go to a static class!
public static IEnumerable<T> FindControlsOfType<T>(this Control control) where T : Control
{
foreach (Control child in control.Controls)
{
if (child is T)
{
yield return (T)child;
}
else
{
foreach (T grandChild in child.FindControlsOfType<T>())
{
yield return grandChild;
}
}
}
}
Page.Title, I got you 😉