Dynamically Generate META tags in ASP.NET Pages with LINQ to SQL

Posted by: Malcolm Sheridan , on 10/2/2009, in Category ASP.NET
Views: 35986
Abstract: The following article demonstrates how to use LINQ to SQL to dynamically generate Meta tags for ASP.NET pages.
Dynamically Generate META tags in ASP.NET pages with LINQ to SQL
 
Earlier this year I wrote an article on how to Dynamically Generate Meta Tags for ASP.NET Pages using LINQ To XML. I received allot of feedback from readers on that article, and some people pointed out this information should be coming from a database. Well I thought it was time to address this by writing an article on how to generate this information from a database.
The first step is creating the database. I have created a database called MetaTags and it contains two tables. One called Pages and the other called MetaData. The script to create the database  (MetaTags.sql) can be downloaded along with the source code (link given at the end) of this article, but the tables will end up looking like this:




Page_MeataData
 
The Page table will store the name of the page, and the MetaData will store Meta information on the page. This is a one to many relationship as one page can have multiple Meta tags.
 
The next step in to create a new web application project. Open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application. I’m going to use LINQ to SQL in this example as I think it’s a great piece of technology. Right click on the project and choose Add > New Item > LINQ to SQL Classes. Name the new file MetaTags. Once the file is created, connect to your SQL Server and drag and drop the two tables created in the previous step. Your file should look like this:
 
Page_MetaData_1
 
Save and build your project. Now that’s done the last thing to do is add a master page to the project. Right click the project and choose Add > New Item > Master Page. When the page is created, open up the code behind file and add the following code:
 
C#
 
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
      {
            FetchMetaData();   
}           
}
 
private void FetchMetaData()
{
using (var dc = new MetaDataDataContext())
      {
            var query = from page in dc.Pages
                  join meta in dc.MetaDatas on page.PageId equals meta.PageId
                  where page.PageName.ToLower() == Request.Url.AbsolutePath.ToLower()
                  select new
                  {
                        Key = meta.KeyName,
                        meta.Value
};
 
foreach (var item in query)
            {
                  HtmlMeta meta = new HtmlMeta();                   
                  meta.Name = item.Key;
                  meta.Content = item.Value;
                  Page.Header.Controls.Add(meta);
}
}
}
 
VB.NET
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not IsPostBack) Then
             FetchMetaData()
End If
End Sub
 
Private Sub FetchMetaData()
Using dc = New MetaDataDataContext()
             Dim query = From page In dc.Pages _
                          Join meta In dc.MetaDatas On page.PageId Equals meta.PageId _
                          Where page.PageName.ToLower() = Request.Url.AbsolutePath.ToLower() _
                          Select New
                               Key = meta.KeyName, meta.Value
 
For Each item In query
                        Dim meta As New HtmlMeta()
                         meta.Name = item.Key
                         meta.Content = item.Value
                         Page.Header.Controls.Add(meta)
Next item
End Using
End Sub
 
In the code above, the code will run on each page request. It executes the LINQ query which returns Meta information for the requesting page:
 
C#
 
var query = from page in dc.Pages
            join meta in dc.MetaDatas on page.PageId equals meta.PageId
            where page.PageName.ToLower() == Request.Url.AbsolutePath.ToLower()
select new
            {
                  Key = meta.KeyName,
                  meta.Value
};
 
VB.NET
  
Dim query = From page In dc.Pages _
            Join meta In dc.MetaDatas On page.PageId Equals meta.PageId _
            Where page.PageName.ToLower() = Request.Url.AbsolutePath.ToLower() _
            Select New
                  Key = meta.KeyName, meta.Value
 
If records are found, the foreach loop will enumerate through each record and create a new HtmlMeta object. This object allows programmatic access to the <head> tag on the server:
 
C#
 
foreach (var item in query)
{
      HtmlMeta meta = new HtmlMeta();                    
meta.Name = item.Key;
      meta.Content = item.Value;
      Page.Header.Controls.Add(meta);
}
 
VB.NET
  
For Each item In query
      Dim meta As New HtmlMeta()
meta.Name = item.Key
       meta.Content = item.Value
       Page.Header.Controls.Add(meta)
Next item
 
That’s it. When you run the application you’ll see the HTML Meta tags have been added to the page:
 
HTML
 
One thing I will point out is that I have used Request.Url.AbsolutePath in my LINQ query. This property will return the absolute path of the requesting page, so for example if the requesting page is coming from the Default.aspx page in the root directory it will appear as this:
 
/Default.aspx
 
I chose to leave this instead of querying for the exact page name because for the simple fact that if you have a sub folder, there’s a chance you could have a page that is the same name as another page in a different folder. So if you have a folder called Admin and you want to add Meta tags to it, you’ll need to add the absolute path into the database:
 
/Admin/Default.aspx
 
This way you’ll always fetch the correct Meta tags for the requested 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. Yet another good use for LINQ! The entire source code of this article can be downloaded from here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

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!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
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


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Mostafa on Wednesday, October 6, 2010 5:18 AM
Hi,
If we need friendly URL , and using using some technique like URLRouting , Is there any problem ?

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook