Friday, October 2, 2009

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

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

No comments:

Post a Comment