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
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015