Eric Bergman-Terrell's Blog

ASP.NET Tip: How to programmatically add <META> tags to .aspx page
October 4, 2010

The HTML <META> tag is used to store information about a page. Including <META> tags in your pages may make your site more search engine friendly. <META> tags must be nested immediately under the <HEAD> tag. You can specify a page's keywords and description with <META> tags. For example, the old ASP.NET implementation of my articles.aspx page had the following <META> tags:

<meta name="keywords" content="Articles, Eric Bergman-Terrell, S3, .NET, C#, dotnet, Web Services, ASP.NET, Windows Forms" />

<meta name="description" content="Magazine articles written by Eric Bergman-Terrell" />

You can programmatically add <META> tags to your pages as follows by populating an HtmlMeta object and inserting it in the page's Header.Controls container. For example, I use the following code to add <META> tags to pages on my site. The keywords object is a DataSet that contains keywords and descriptions for most of the pages on the site:

private void AddMetaTags()
{
    if (keywords != null)
    {
        string filter = string.Format("Page = '{0}'", Request.Url.AbsolutePath);

        DataRow[] rows = keywords.Tables[0].Select(filter);

        if (rows.Length == 1)
        {
            string keywordText = rows[0]["Keywords"] as string;
            string descriptionText = rows[0]["Description"] as string;

            if (keywordText != null || descriptionText != null)
            {
                if (keywordText != null)
                {
                    // Create a META tag.
                    HtmlMeta meta = new HtmlMeta();

                    meta.Attributes.Add("name", "keywords");
                    meta.Attributes.Add("content", keywordText);

                    Header.Controls.Add(meta);
                }

                if (descriptionText != null)
                {
                    // Create a META tag.
                    HtmlMeta meta = new HtmlMeta();

                    meta.Attributes.Add("name", "description");
                    meta.Attributes.Add("content", descriptionText);

                    Header.Controls.Add(meta);
                }
            }
        }
    }
}
Keywords: Meta Tags, SEO, HtmlMeta, ASP.NET

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021
Vault (Desktop) Version 0.72 ReleasedOctober 6, 2021
EBT Compass is Now Available for Android DevicesJune 2, 2021