Dynamically Generate Meta Tags for ASP.NET Pages using LINQ To XML
Posted by: Malcolm Sheridan ,
on 5/19/2009,
in
Category ASP.NET
Abstract: The following article demonstrates how to use LINQ to XML to dynamically generate meta tags for different ASP.NET pages.
Dynamically Generate Meta Tags for ASP.NET Pages using LINQ To XML
We all know how important it is to use meta tags when you’re building an internet web site. Meta tags provide metadata about the HTML document. They are not rendered in the browser but are used by search engines to parse web pages. The following article demonstrates how to store meta tags for each page in an XML file and how to use LINQ to read the XML data and dynamically create meta tags for each page in your website.
Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.
Add a Master Page to the project. Once that is completed, add a Web Content Page and select the newly created Master Page as the Master Page.
The next step is to create a new folder in the web site to demonstrate all pages in the website will have dynamic meta tags at runtime. Right click the website and choose Add > New Folder. Name the new folder ChildFolder. After this add a new Web Content Page to this folder. Leave the default name as this is not important.
Now that we have two pages in different folders, it’s now time to create an XML file that contains the data for the meta tags. Right click the website and choose Add > New Item > XML File. Name the file TagData.xml and add the following XML:
<metaTags>
<tags pageName="/WebForm1.aspx">
<tag name="keyword" value="This is a keyword"></tag>
<tag name="description" value="This is a description"></tag>
<tag name="author" value="malcolm sheridan"></tag>
</tags>
<tags pageName="/ChildFolder/WebForm1.aspx">
<tag name="keyword" value="This is a keyword for the child pages"></tag>
<tag name="description" value="This is a description for the child pages"></tag>
<tag name="author" value="malcolm sheridan for this page too"></tag>
</tags>
</metaTags>
In the XML above I have created a parent node called metaTags. Inside I have created a tags node which contains a pageName attribute. That value is how we will match the current requested page to the XML data. Each tags node contains a tag node that corresponds to the meta data we want sent to the browser. In this example I want to set meta tags for the all the pages to have keyword, description and author meta tags, but the values rendered to the browser will differ depending on what page the user is on. In a real world scenario this information would be stored inside a database, but I decided to keep this data inside an XML file to keep it simple and focus on how to do this.
Having outlined what meta tags we want sent to the browser, we now have to write the code that will read the XML file and dynamically add the meta tags at runtime. Seeing as though we’re using Master Pages this is the ideal spot to add it. Add the following code to read the XML file:
C#
XDocument doc = XDocument.Load(Server.MapPath("~/TagData.xml"));
var metaTags = doc.Descendants("tag")
.Where(o => o.Parent.Attribute("pageName").Value == Request.Url.AbsolutePath)
.Select(o => new
{
Value = o.Attribute("value").Value,
Name = o.Attribute("name").Value
});
VB.NET
Dim doc As XDocument = XDocument.Load(Server.MapPath("~/TagData.xml"))
Dim metaTags = doc.Descendants("tag").Where(Function(o) o.Parent.Attribute("pageName").Value = Request.Url.AbsolutePath).Select(Function(o) New With {Key .Value = o.Attribute("value").Value, Key .Name = o.Attribute("name").Value})
For flexibility and ease of use I have decided to use the power of LINQ to XML to read the XML data. To start with the XML document is load into an XDocument object. From there I have created a LINQ query to return all the tag nodes where the parent node has an attribute called pageName and the value is equal to the current page. Then the object returned is an anonymous type that has a Value and Name property. The values of those properties are the value and name attribute values.
Now that we have the data in memory, the next step is to create the meta tag and add it to the page dynamically. To do this you use the HtmlMeta class. This allows you programmatic access to the HTML meta tags. Add the following code below to your project:
C#
foreach (var item in metaTags)
{
HtmlMeta meta = new HtmlMeta();
meta.Name = item.Name;
meta.Content = item.Value;
Page.Header.Controls.Add(meta);
}
VB.NET
For Each item In metaTags
Dim meta As New HtmlMeta()
meta.Name = item.Name
meta.Content = item.Value
Page.Header.Controls.Add(meta)
Next item
The foreach loop enumerates through each item returned from the LINQ query. It assigns the Name and Content value to the HtmlMeta object. Finally the object is added to the page by calling Page.Header.Controls.Add(meta). Run the project and once the default page has loaded, view the HTML source and you’ll see the meta tags have been added to the website.
Browsing to the second page and viewing the HTML source, you’ll find the meta tags have been added to the page but they’re different values from the previous page.
I hope you have found this article of interest. Meta tags are a great way to describe your website to the outside world, and this way you can dynamically add this data with LINQ. Is there anything LINQ can’t do? The entire source code of this article can be downloaded from here.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @
malcolmsheridan