Programmatically Adding Meta Tags to ASP.NET 2.0 Pages
The Problem
I was recently looking for a way to programmatically add and update Meta Tags in ASP.NET 2.0. This is a fairly simple thing to do with standard .aspx pages. Just add ID and Runat attributes to the Head element and reference the control in the code behind. However, this is not so simple when working with MasterPages, which I am. What I wanted was a way to:
- Add a new Meta tag
- Change the
contentattribute of an existing Meta Tag - Append data into the
contentattribute of an existing Meta Tag - Do any of the above from a MasterPage, Page or User Control
AddMetaTag Utility in App_Code
Initially, in my Master Pages I added a AddMetaTag method, which the Content Pages could call. However, this did not allow me to call the method from User Controls. It was also a maintenance pain, since the code had to be added to each Master Page.
A simple solution was to take advantage of the App_Code folder and add a Utility Class, which could be called from anywhere in the Web project. The AddMetaTag method needs three parameters passed, the Page reference and strings for the Name and Content attributes of the Meta Tag.
C#
Utilities.cs (in App_Code)
public class Utilities {
public static void AddMetaTag(Page thisPage, string name, string content) {
...
}
}
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e) {
Utilities.AddMetaTag(this.Page, "author", "Josh Salwen");
}
VB
Utilities.vb (in App_Code)
Public Class Utilities
Public Shared Sub AddMetaTag(ByVal thisPage As Page, ByVal name As String, ByVal content As String)
...
End Sub
End Class
Default.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Utilities.AddMetaTag(Me.Page, "author", "Josh Salwen")
End Sub
Adding a New Meta Tag
Using the System.Web.UI.HtmlControls.HtmlMeta class makes it easy to create a Meta Tag.
C#
HtmlMeta meta = new HtmlMeta();
meta.Name = "Author";
meta.Content = "Josh Salwen";
VB
Dim meta As New HtmlMeta
meta.Name = "Author"
meta.Content = "Josh Salwen"
The trick is adding it into the HTML Head element.
By default, Visual Studio 2005 adds a runat="server" to the Head element in both .master pages and .aspx pages (if it is not a content page which references a Master Page). As long as the runat="server" is not removed, the Page.Header property can be accessed. If it is removed, then it is not possible to access the Page.Header, so when referencing the Header is is important to make sure it is not null (or Nothing).
Once the Page.Header is referenced, then you create a new HtmlMeta object and add it to the Page.Header Controls.
C#
public static void AddMetaTag(Page thisPage, String name, String content) {
HtmlHead header = (HtmlHead)thisPage.Header;
if (header != null) {
HtmlMeta meta = new HtmlMeta();
meta.Name = name;
meta.Content = content;
header.Controls.Add(meta);
}
}
VB
Public Shared Sub AddMetaTag(ByVal thisPage As Page, ByVal name As String, ByVal content As String)
Dim header As HtmlHead = DirectCast(thisPage.Header, HtmlHead)
If Not IsNothing(header) Then
Dim meta As New HtmlMeta
meta.Name = name
meta.Content = content
header.Controls.Add(meta)
End If
End Sub
Updating an Existing Meta Tag
Once the functionality was in place to add a Meta Tag, I just needed to add the ability to update an existing tag. In order to do this, the method does the following:
- Loops through the
Controlsin the Header - Checks if the
Controlis anHtmlMeta - Checks if the
Nameattributes are the same - Updates the
Contentattribute and exits the method
C#
public static void AddMetaTag(Page thisPage, String name, String content) {
HtmlHead header = (HtmlHead)thisPage.Header;
if (header != null) {
HtmlMeta meta = new HtmlMeta();
// Loop through all the controls in the Header
foreach (Control ctrl in header.Controls) {
// Check if the control is a Meta Tag
if (ctrl is HtmlMeta) {
// Get the Meta Tag and check if the name is the same
meta = (HtmlMeta)ctrl;
if (name.Equals(meta.Name, StringComparison.InvariantCultureIgnoreCase)) {
// Since the Meta Tag already exists, simply update and exit
meta.Content = content;
return;
}
}
}
meta = new HtmlMeta();
meta.Name = name;
meta.Content = content;
header.Controls.Add(meta);
}
}
VB
Public Shared Sub AddMetaTag(ByVal thisPage As Page, ByVal name As String, ByVal content As String)
Dim header As HtmlHead = DirectCast(thisPage.Header, HtmlHead)
If Not IsNothing(header) Then
Dim meta As New HtmlMeta
' Loop through all the controls in the Header
For Each ctrl as Control in header.Controls
' Check if the control is a Meta Tag
If TypeOf ctrl Is HtmlMeta Then
' Get the Meta Tag and check if the name is the same
meta = DirectCast(ctrl, HtmlMeta)
If name.Equals(meta.Name, StringComparison.InvariantCultureIgnoreCase) Then
' Since the Meta Tag already exists, simply update and exit
meta.Content = content
Return
End If
End If
Next
meta = New HtmlMeta
meta.Name = name
meta.Content = content
header.Controls.Add(meta)
End If
End Sub
… And a Few More Things
I noted above that I want to be able to append data as well. I also want to compare the Name and Lang attributes, since you can add the same Meta Tag for different languages. I have included this code in the source code, if you want to check it out.
And finally, in the ASP.NET 2.0 Alpha, the Header had MetaData.Add (I think that is what it was called), so Microsoft was thinking about this at one point. I’m not sure what happened.
September 25th, 2009 at 3:06 pm
ewasoligy…
Guide to Better Grades: How to Ace your Psychology… …
June 26th, 2010 at 1:39 am
PillSpot.org. Canadian Health&Care.Special Internet Prices.No prescription online pharmacy.Pillspot.org. Vitamins@buy.online” rel=”nofollow”>.…
Categories: Pain Relief.Blood Pressure/Heart.Mens Health.Antidepressants.Stop SmokingMental HealthAnxiety/Sleep Aid.Antibiotics.Stomach.Womens Health.Anti-allergic/Asthma.Skin Care.Eye Care.Weight Loss.Vitamins/Herbal Supplements.Antiviral.Antidia…