Recently, I was looking for a simple way to control the TITLE and META tags on aspx pages. I needed to use standard aspx pages as created by Visual Studio derived from the standard System.Web.UI.Page. At first I tried changing the Title tag to a server HTML control, by adding
<Title id=PageTitle runat=server></Title>
But it seems that the VS IDE doesn't like this and it occasionally removed those attributes without asking, though I couldn't work out when. So instead I decided to use a UserControl, with an asp:Literal control in it, and place it in the Head section of each page. instead of the title.
First I created an XML file with the details of the tags for the pages in my site. Here's an example:
<?
xml version="1.0" encoding="utf-8" ?>
<HtmlTags>
<Tags>
<FolderAndFile>DEFAULT</FolderAndFile>
<Title>.net training, consultancy and development</Title>
<Description>.net training, consultancy and development with bbits in the uk</Description>
<Keywords></Keywords>
</Tags>
<Tags>
<Tags>
<FolderAndFile>services/default.aspx</FolderAndFile>
<Title>.net services from bbits</Title>
<Description>training, consultancy and development services</Description>
<Keywords></Keywords>
</Tags>
</HtmlTags>
Then I created a UserControl with a Literal control - the HTML in it just looks like this:
<asp:Literal id="Literal1" runat="server"></asp:Literal>
In the code behind in the control I added the following to the Page Load event of the Control
string
folderAndFile = WebTier.Utils.GetFolderAndFileName(); //this is a call to a static util method I have that returns the folder and file name of the current page without the site name.
DataSet ds = new DataSet();
ds.ReadXml(Request.PhysicalApplicationPath + @"/data/HTMLTags.xml"); //my xml file is stored in the data folder off the root of my site.
DataView dv = new DataView(ds.Tables[0],"FolderAndFile='" + folderAndFile + "'","",DataViewRowState.CurrentRows);
string tags = @"<Title>{0}</Title><meta name=""Description"" value=""{1}""><meta name=""keywords"" value=""{2}"" >";
if (dv.Count ==0)
{
dv.RowFilter = "FolderAndFile='DEFAULT'";
}
Literal1.Text = string.Format(tags,dv[0]["Title"],dv[0]["Description"],dv[0]["Keywords"]);
Then all I had to do for each page, was make sure it had a the UserControl in the Head section and that any existing Title tag was removed; and put an entry for it in the xml file of course (though with no entry it will use the DEFAULT). I went on to cache the dataset with the xml file in it to speed the access up a bit...
Works a treat!