ASP.NET HtmlMeta Example

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. You can add this tag with HtmlMeta using ASP.NET and the C# language.

Meta tag

Example

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.

This example C# code uses HtmlMeta to add meta tags to HTML.

Example that adds meta tag [C#]

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);
}
Note

Description. 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.

Output of above code [HTML]

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

Summary

ASP.NET web programming framework

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.

ASP.NET Tutorials
.NET