Creating a Tag Cloud for Your ASP.NET Blog


Most of the blogs display a set of tags or keywords in the form of a Tag Cloud. A tag cloud presents the keywords in font sizes proportional to the number of blog posts having that tag. If you are using some blogging website or using some open source blogging engine you already have a tag cloud ready. However, if you are building your own blog engine or website you will need to build the tag cloud on your own. This article shows how to do just that.

What is a Tag Cloud?

A tag cloud is a bunch of tags or keywords found on your blog. Have a look at the following figure that displays a tag cloud:

Tag Cloud
Figure 1: Tag Cloud

As you can see, tag cloud gives some visual indication about the number of entries for a specific tag. In the above example, tag ASP.NET appears in more posts as compared to other tags such as Components and Windows Forms. Each tag from a tag cloud will usually be a hyperlink and clicking on that link will generally present a list of blog posts having that tag.

Sample Database

To begin creating a tag cloud, create a new ASP.NET website and add a new SQL Server database to its App_Data folder. The SQL Server database will contain a single table, BlogPosts, whose schema is shown in the following figure:

Table Schema
Figure 2: Table Schema

As you can see the BlogPosts table has a simple structure (of course, in a real world blog engine you will have many other columns). The Tags column stores | separated list of tags belonging to a blog post. e.g. ASP.NET|AJAX|jQuery

Once you create the database add a few records for testing purpose. Make sure to keep the density of tags in such a way that you can confirm that tags are displayed as expected in the tag cloud.

Controlling the Look and Feel of Tag Hyperlinks

One way to control the look and feel of the tag hyperlinks is to use the style attribute of the anchor (<a>) tag and then set the font-size and color CSS properties. Though this works fine, this is not recommended if you are using ASP.NET Themes or separate CSS files to control the look and feel of the website. It is advisable to include the CSS class in the website theme and then use these classes for hyperlinks as required. So, add a new Theme named Default to App_Themes folder and add the following CSS classes to a style sheet file.

    font-family: Arial;
    font-size: 20px;
    color: #FF0000;
    font-family: Arial;
    font-size: 30px;
    color: #993333;
    font-family: Arial;
    font-size: 40px;
    color: #0000FF;
    font-family: Arial;
    font-size: 50px;
    color: #009900;
    font-family: Arial;
    font-size: 60px;
    color: #9900FF;

As you can see, there are five CSS classes, TagSize1 to TagSize5. TagSize1 is the smallest and TagSize5 is the biggest amongst the set of classes. We created only five CSS classes because we will have five font sizes in the tag cloud. You can of course alter this behavior as per your need.

Creating TagCloud User Control

You will create the tag cloud as a User Control so that you can place it in multiple places (say right or left sidebar and at the bottom of the home page). So, add a new user control (TagCloud.ascx) to the website and put a PlaceHolder control on it. You will add HyperLink controls to this PlaceHolder control dynamically. The TagCloud user control needs to access the BlogPosts table to determine the "weight" of each and every tag. To facilitate this data access, add a LINQ to SQL class to the website and drag and drop the BlogPosts table from Server Explorer onto its design surface. This will generate BlogPost LINQ to SQL class as shown below:

BloPost Properties
Figure 3: BloPost Properties

Then go to the Page_Load event handler of the user control and key-in the following code:

protected void Page_Load(object sender, EventArgs e)
    DataClassesDataContext db=new DataClassesDataContext();
    SortedDictionary<string, int> tagsDictionary = new SortedDictionary<string, int>();
    var temp = from row in db.BlogPosts
                select row.Tags;
    int postCount = temp.Count();
    foreach (string tags in temp)
        string[] k = tags.Split('|');
        foreach (string s in k)
            if (tagsDictionary.ContainsKey(s))
                tagsDictionary.Add(s, 1);
    foreach (string s in tagsDictionary.Keys)
        string tagInUrl = Server.UrlEncode(s);
        HyperLink link = new HyperLink();
        link.Text = s;
        link.NavigateUrl = String.Format("~/ShowPostsByTag.aspx?tag={0}", tagInUrl);
        int tagCount = 0;
        tagsDictionary.TryGetValue(s, out tagCount);
        link.CssClass = GetCssClass(tagCount,postCount);
        PlaceHolder1.Controls.Add(new LiteralControl("  "));

The code creates an instance of DataContext and selects tag column for all of the blog posts. The SortedDictionary is intended to store unique tags in sorted fashion so that they appear in the tag cloud in A-Z order. A foreach loop iterates through all the blog post rows and with each iteration the SortedDictionary is populated. Another foreach loop then iterates through all Keys of the tag dictionary (i.e. unique tags). For every tag in the tags dictionary a HyperLink control is created programmatically. The Text property of the new hyperlink is set to the tag name and its NavigateUrl property to ShowPostsByTag.aspx. The tag name is passed to ShowPostsByTag.aspx in the query string. To determine the CSS class that needs to be applied to the hyperlink we use a helper method - GetCssClass. The GetCssClass() method is shown below:

private string GetCssClass(int tagCount, int postCount)
    int result = (tagCount * 100) / postCount;
    if (result <= 20)
        return "TagSize1";
    if (result <= 40)
        return "TagSize2";
    if (result <= 60)
        return "TagSize3";
    if (result <= 80)
        return "TagSize4";
    if (result <= 100)
        return "TagSize5";
        return "";

The GetCssClass() method accepts the total number of occurrences for a tag in the BlogPosts table and the total number of blog posts. Based on this information a percentage "weight" is calculated. Recollect that we have created five CSS classes and hence we divide the result into five slabs. Depending on the slab the CSS class name is returned. You may consider changing the slab values as per your requirements.

Finally, the dynamically generated HyperLink control is added to the Controls collection of the PlaceHolder.

Testing TagCloud User Control

Now that you have built the tag cloud user control, let's test it on a web form. Add a new web form to the website and drag and drop the TagCloud user control on it. Run the web form and you should see something to the screenshot below:

Tag Cloud
Figure 4: Tag Cloud

Of course, tag names and their sizes will vary depending on your sample data. All the tag hyperlinks point to ShowPostsByTag.aspx and pass the tag name as a query string. You can use this query string value in the ShowPostsByTag.aspx page and display all blog posts having that tag (see a sample below).

Blog Posts
Figure 5: Blog Posts

As you can see in the code discussed in the preceding sections, the calculation of tag "weight" will happen every time the web form is loaded. If your blog is being updated once a day then there is no need to recalculate the tag weight as it is going to be the same for this time window. To avoid such repeated processing and improve the performance, you can implement Output Caching in the TagCloud user control.


Tag cloud is an essential ingredient of a blog. A tag cloud displays "weighted" tags as per their number of occurrences in the blog posts. This article illustrated how a tag cloud can be built for your own blog. The TagCloud user control thus created can then be used on web forms and master pages.

About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Related Articles



  • web development

    Posted by HANISHA on 09/28/2016 04:42am

    Great post Very useful information !its really useful in custom application development

  • Giving

    Posted by santosh on 06/07/2016 09:56pm

    As the applicants who are applying for government jobs your website, it also helped me on many occasions when I needed regular updates related to jobs. As my suggestion include more previous year papers which helps us more in p[reparing for the exams

  • Sarkari Result

    Posted by Navatha on 11/02/2015 02:57am

    Good article with excellent idea! I appreciate your post.Regards Sarkari Result

  • Sarkari Result

    Posted by sarkari on 09/28/2015 04:47am

    interesting article Regards Sarkari Result

  • Thanks for the tutorial

    Posted by David on 09/01/2015 08:58am

    Problem with testing TagCloud solved for my website

  • medical assistant

    Posted by Susanne Green on 03/14/2015 11:42am

    Great! We always talk about quality not the quantity. Thanks Susanne Green medical assistant

  • Elige a la plancha de pelo depende de la longitud del cabello y el moldeador, dispuestos a gastar

    Posted by xynnlm951 on 07/25/2013 09:24pm

    pelo ghd es hermosa arma secreta peinado de una mujer. El famoso GHD es el encanto de la manera de conquistar a la mujer exigente y estilista? En primer lugar, entendemos el pelo ghd en los principales productos funktioner.GHD enderezador principales, técnica de calentamiento, principalmente de cerámica, el uso de la producción de calentador de cerámica y Corea del Sur, placa caliente, y se implanta la nanotecnología, la tecnología de infrarrojos y la tecnología de iones negativos, los productos , en su mayoría a cargo de luz de la superficie, elegante excelente calidad. Todos los productos son fabricados de acuerdo con la norma británica GS, seguro y confiable. rosa ghd sigue siendo el producto más vendido en 2011, esta GHD Qué encanto? [url=]planchas ghd[/url] plancha de pelo ghd utiliza placas de cerámica para liso, fácil de moldear. Control de la tensión, puede crear el más apropiado entre las placas cerámicas de pelo liso. El producto también tiene el mismo anión, la conservación de hacer que el cabello suave y brillante, para evitar el pánico. Cuerpo con una configuración de calor digitales, pantalla digital hace que sea fácil seleccionar la función deseada o ajustar la forma de la temperatura. Puede ayudar a elegir el pelo bien y la temperatura deseada. Pulse un botón, tendrá un efecto perfecto de inmediato. 1 función de apagado automático hora le permite utilizar más paz de la mente. Planchas ghd como operación segura y simple. Ocupar gran cuota de mercado. Convertido en una moda de comprar. Debido a esto, a menudo parece falsa, por lo que cada vez más personas están comprando auténticos planchas ghd. Nuestra tienda, aunque las ventas de negro pelo ghd. Pero somos productos ghd regulares. No traen todo tipo de daño fuego falso. Nuestro producto de mapa con el mapa físico es exactamente el mismo. Para asegurar que los productos reales y fiables. Y vendemos planchas ghd baratas, 7 * 24 funciones en línea, usted puede comprar en cualquier momento. Siempre y cuando haya seleccionado el tipo deseado, complete la información personal, etc temas relacionados, el producto puede ser enviado directamente a las manos de espera. Por favor, comprar productos ghd sentimientos antes, mira a nuestra política de privacidad, Quiénes somos, transporte, preguntas más frecuentes y las políticas más relevantes, esto le ayudará a comprar nuestros productos. Gracias por tu colaboración. [url=]planchas ghd[/url] Somos ghd planchas para el pelo red profesional, tenemos un trabajo en equipo fuerte para llegar a más gente sobre la necesidad de ghd constantemente actualizada constantemente transformere.du tiene una buena y agradable de compras miljø.og venta de planchas ghd, bajo price.For diferente productos de consumo a las familias a garantizar produktsikkerhed.Danmark es primera monarquía constitucional del mundo. Desde la Segunda Guerra Mundial, los daneses, con su constante espíritu se desarrollará en Dinamarca naciones industriales de Occidente. Su economía es un desarrollo gradual. Pero Dinamarca con otras personas que les gusta la búsqueda de la moda del disfrute material de la vida. Pero ellos tienen sus propios límites. Ellos saben cuándo ir demasiado lejos. sentido estético

  • duLKv eRj USXL

    Posted by WZptwrROcu on 06/05/2013 07:55pm

    buy propecia can you buy propecia online no prescription - much does propecia cost boots

  • toms on sale

    Posted by carpinteyrocux on 03/11/2013 11:28pm

    793150 [b]Tags:[url=]toms outlet[/url]|[url=]toms outlet[/url]|[url=]toms sale[/url]|[url=]discount toms[/url]|[url=]cheap toms[/url] &Links: [url=]toms shoes retailers[/url][/b] as long as that someone prefer Bottega Veneta stepped up to the plate.A curvaceous wedge can't be marked for a big alteration of lesson,as I write this blog post. I equitable got news from the publisher of my present paperback thatStart Something that Mattersis instantly a 1 New York Times Best Seller! Never among my wildest dreams did I imagine this would occur plus all I can think of right now namely how grateful I am apt each plus everyone of you that has supported TOMS over the past five years. This moment goes apt you!With all my adore plus thanks,plus I adore the way the colors work together The shades of ruddy turquoise,but it largely lacks the inexplicable missteps that have characterized Choo's recent collections. This is a solid, set deep amid the heart of London's maximum creative and cultural 15 min The 2010 edition brings you more of everything: more stages,As part of the last show to be subject to Mr. McQueen's direct approval I anticipate these aspiration be both coveted and collectible.And, the finish with its crocodile seal detailing is more than barely silver,

  • купить маскарадный костюм

    Posted by Fapaveactuach on 02/22/2013 01:21am

    Уважаемые господа!Оформить заказ выгодный для Вас! Тогда читайте новость - красивые платья картинки женские сумки интернет и дорогая бижутерия купить красивые платья фото ... Хороших Вам покупок! :::::::::::: Kamagra tablets next day shipping - Buy and purchase Kamagra Online or kamagra generica - online drug stores Kamagra where to Buy , Kamagra direct 4 u - what is Kamagra used for !!!!

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date