Using Dynamic Meta Tags In .NET

I’ve been working on an ASP.NET project recently and came across the need to dynamically set the values for all of the HTML tags. The site is built using ASP.NET master pages and I have a default page for each section that the URL Routing functionality calls to load up the content. Each page can have it’s own set of meta information, which is read from the database along with the other page content information. While searching for the best way to do this I found an available class named HtmlMeta. Using this class will allow you to set your meta information as you need to, from anywhere in your code. I used this class within a function I created in my main master page. Each of my content page handlers call the function living in the master page and pass it the correct data. I also have the function set up for the scenario that null values are passed (meaning the client did not enter in meta information in the CMS tool). If no values are provided it sets up default values for each tag. In the end it became a rather simple solution.

Below is the function that lives in my code behind page of the master file:

<code lang="csharp[lines]">public void SetMetaInfo(string pageTitle, string pageDescription, string pageKeywords)<br></br>  
    {<br></br>
        if (pageTitle == null || pageTitle.Length == 0)<br></br>
            pageTitle = "Default Title";```

 if (pageDescription == null || pageDescription.Length == 0)  
 pageDescription = "Default Meta Description";

 if (pageKeywords == null || pageKeywords.Length == 0)  
 pageKeywords = "Default Meta Keywords";

 Page.Header.Title = pageTitle;

 HtmlMeta _metaDescription = new HtmlMeta();  
 _metaDescription.Name = "Description";  
 _metaDescription.Content = pageDescription;  
 Page.Header.Controls.Add(_metaDescription);

 HtmlMeta _metaKeywords = new HtmlMeta();  
 _metaKeywords.Name = "Keywords";  
 _metaKeywords.Content = pageKeywords;  
 Page.Header.Controls.Add(_metaKeywords);  
 }

And the code below lives in my content handler page. It reads my content from the database (using LINQ) and calls our function in the master page. Take notice of how the function is called within the master page. We use this.Master so the code knows to call the function that is within our master page code behind.

protected void loadContent(String page)


{

contentCS _content = new contentCS();

var qry = _content.GetByAlias(
page);

pageTitle.InnerText = qry.name;

mainContent.Text = HttpUtility.HtmlDecode(qry.body);```

this.Master.SetMetaInfo(qry.metatitle, qry.metadescription, qry.meta_keywords);
}

Comments

comments powered by Disqus