Dot Net Perls

HtmlMeta Example in ASP.NET

by Sam Allen - Updated May 20, 2009

Problem. You want to add meta tags with ASP.NET in code-behind that can be used by Googlebot. Google requires that webmasters have a tag that indicates that you own the site before it lets you look at its information. Solution. Here we see how to add this tag to your website using ASP.NET and the C# programming language.

Meta tag

1. Using HtmlMeta instances

In a master page setup, content pages do not have hard-coded HTML head sections. You need to add meta tags dynamically. ASP.NET provides a handy class called HtmlMeta in the System.Web namespace. Here we use that class in a Page_Load event.

protected void Page_Load(object sender, EventArgs e)
{
    // This adds a metatag dynamically when run.
    AddMetaTag("verify-v1", "_NfoJpEJ/U+APc+dgVA1UV0YJqdAa+YKtP106LNZDl8=");
}

void AddMetaTag(string name, string content)
{
    HtmlMeta meta = new HtmlMeta();
    meta.Name = name;
    meta.Content = content;

    // Add the control to the HTML.
    Page.Header.Controls.Add(meta);
}

Description of the example. It uses a custom method. We use a convenience function called AddMetaTag to create a new HtmlMeta object. Its Name and Content properties are then set to the parameter values.

Next steps. The elements are added to Page.Header. Finally, HtmlMeta is added to the Page.Header.Controls collection. This instructs ASP.NET to place the HTML metatag in the HEAD block, which I show an example of next.

<!-- Head contents come before this... -->
<meta name="verify-v1" content="_NfoJpEJ/U+APc+dgVA1UV0YJqdAa+YKtP106LNZDl8=" />
</head>

2. Summary

Here we looked at how you can use HtmlMeta in ASP.NET. HtmlMeta here makes fewer typos likely than hard-coding the HTML in various pages. Like HtmlTextWriter does for writing HTML, this approach for meta elements can reduce your risk of hard-to-find bugs.

Dot Net Perls
Web Forms | asp:Literal Use | LiteralControl Example | Master Page SEO | Master Page Use | Visible Property
C# | Dictionary StringComparer Tip | DateTime.TryParse Example | Reflection Field Example | Validate Characters in String
© 2009 Sam Allen. All rights reserved.