Creating tag cloud using ASP.NET MVC and Entity Framework

I am building events site on ASP.NET MVC 3 and Entity Framework. Today I added tagging support to my site and created simple tag cloud. In this posting I will show you how my tag cloud is implemented. Feel free to use my code if you like it.

Model

Events and tags modelTo give you better idea about the structure of my classes here is my Entity Framework model. You can see that events and tags have many-to-many relationship defined between them.

In database I have one table between events and tags but as this table contains primary key that is 100% made up of foreign keys of events and tags table then Entity Framework is able to create many-to-many mapping automatically without creating additional object for relation.

You can also see that there is Events navigation property defined for Tag class. It is not good idea to create more navigation paths than you need and in the case of Tag class we need this navigation property.

Tag cloud solution

To create tag cloud we need to go through the following steps:

  1. Create Tag table and bind it to Event.

  2. Update your Entity Framework model to reflect new changes made to database.

  3. Add some classes that hold tag cloud data (TagCloud is container class that keeps collection of MenuTag objects).

  4. Create extension method to Html class that generates tag cloud.

I started with code I found from Mikesdotnetting blog posting Creating a Tag Cloud using ASP.NET MVC and the Entity Framework and worked out my own solution. Referred posting was great help for me and let’s say thanks to author for sharing his ideas with us.

Tag cloud implementation

As a first thing let’s create the class that holds tag data. I named this class as MenuTag.

public class MenuTag
{
   
public string
Tag;
   
public int Count;
}

Tag is the title of tag and Count shows how many events are tagged with this tag.

Next we need the class that packs everything up and provides us with tag rank calculation. For that I defined class called TagCloud.

public class TagCloud
{
   
public int
EventsCount;
   
public List<MenuTag> MenuTags = new List<MenuTag
>();

   
public int GetRankForTag(MenuTag
tag)
    {
       
if
(EventsCount == 0)
           
return
1;

       
var
result = (tag.Count * 100) / EventsCount;
       
if
(result <= 1)
           
return
1;
       
if
(result <= 4)
           
return
2;
       
if
(result <= 8)
           
return
3;
       
if
(result <= 12)
           
return
4;
       
if
(result <= 18)
           
return
5;
       
if
(result <= 30)
           
return
6;
       
return result <= 50 ? 7 : 8;
    }
}

Now we have to add new method to our Entity Framework model that asks data from database and creates us TagCloud object. To add new methods to model I am using partial classes.

public partial class EventsEntities
{
   
private IQueryable<Event
> ListPublicEvents()
    {
       
var query = from e in
events
                   
where
e.PublishDate <= DateTime.Now
                            && e.Visible
                   
orderby e.StartDate descending
                    select
e;
       
return
query;
    }
   
public TagCloud
GetTagCloud()
    {
       
var tagCloud = new TagCloud
();
        tagCloud.EventsCount = ListPublicEvents().Count();
       
var query = from t in
Tags
                   
where
t.Events.Count() > 0
                   
orderby
t.Title
                   
select new MenuTag
                    {
                        Tag = t.Title,
                        Count = t.Events.Count()
                    };
        tagCloud.MenuTags = query.ToList();
       
return tagCloud;
    }
}

And as a last thing we will define new extension method for Html class.

public static class HtmlExtensions
{
   
public static string TagCloud(this HtmlHelper
helper)
    {
       
var output = new StringBuilder
();
        output.Append(
@"<div class=""TagCloud"">"
);

       
using (var model = new EventsEntities
())
        {
           
TagCloud
tagCloud = model.GetTagCloud();

           
foreach (MenuTag tag in
tagCloud.MenuTags)
            {
                output.AppendFormat(
@"<div class=""tag{0}"">"
,
                                    tagCloud.GetRankForTag(tag));
                output.Append(tag.Tag);
                output.Append(
"</div>"
);
            }
        }

        output.Append(
"</div>"
);

       
return output.ToString();
    }
}

And you are almost done. I added my tag cloud to my site master page. This is how what you should write to show tag cloud in your view:

    @Html.Raw(Html.TagCloud())

You can also go on and create partial view but then you have to give data to it through your view model because writing code behind views is not a good idea. If you look at my extension method you will see it’s simple and short and that’s why I prefer to keep it this way.

Conclusion

ASP.NET MVC and Entity Framework make it easy to create modern widgets for your site. Just keep as close to ASP.NET MVC framework as you can and orchestrate it with Entity Framework models. In this posting I showed you how to create simple tag cloud component that plays well together with ASP.NET MVC framework. We created some classes where we keep our data. Tag cloud data is coming from Entity Framework model and tag cloud is included in views using Html extension method.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    53 thoughts on “Creating tag cloud using ASP.NET MVC and Entity Framework

    • April 28, 2011 at 2:33 pm
      Permalink

      You can return MvcHtmlString instead of string to avoid using Html.Raw()

    • April 28, 2011 at 6:10 pm
      Permalink

      Slawek, what’s the difference? This way or other we have to write too much :)

    • October 31, 2011 at 3:26 pm
      Permalink

      Great article. One question – can you share how you are handling the insertion of the events and tags into the respective tables?

    • Pingback:ASP.NET MVC: Implementing CheckBoxList | Gunnar Peipman - Programming Blog

    • April 4, 2025 at 6:16 pm
      Permalink

      Great site you have here.. It’s difficult to find high-quality writing like yours these days.
      I honestly appreciate individuals like you! Take care!!

    • April 4, 2025 at 7:48 pm
      Permalink

      Quality content is the secret to invite the users to pay a visit
      the website, that’s what this website is providing.

    • April 6, 2025 at 12:06 am
      Permalink

      I’m really inspired together with your writing abilities and also with the structure to
      your weblog. Is that this a paid topic or did
      you customize it yourself? Either way stay up the nice high quality writing,
      it is uncommon to look a great weblog like this
      one these days..

    • April 6, 2025 at 2:08 am
      Permalink

      At this time it looks like WordPress is the best blogging platform available
      right now. (from what I’ve read) Is that what
      you’re using on your blog?

    • April 9, 2025 at 2:03 pm
      Permalink

      I’m really loving the theme/design of your weblog.

      Do you ever run into any browser compatibility issues?
      A couple of my blog visitors have complained about my site
      not operating correctly in Explorer but looks great in Opera.
      Do you have any solutions to help fix this issue?

    • April 10, 2025 at 1:10 pm
      Permalink

      By the entrance to the Melbourne Art Fair is a major commission by Dawn Ng
      – a video of a frozen block of pigment, that has thawed over 20 hours.

      Condensed into a 20-minute video, it’s mesmerising, disconcerting and a reminder of the brain-melting effects of rapidly
      consuming vast amounts of contemporary art.

      The Melbourne Art Fair, which opens on Thursday, offers work by more than 100 artists from 70 galleries and Indigenous art centres.

      Held at the Melbourne Exhibition and Convention Centre, it’s a chance to see some of the latest work by leading
      artists and check out large-scale commissions that will soon be
      headed for art institutions.

      One of these commissions is a tubular steel installation by
      Auckland-based artist Yona Lee, that sees her using kinetic elements for the first time.

      Could this be the first ever artwork to deploy tubes, clocks, lamps, fans …

      and robot vacuums?

      The artwork titled Smart sculpture incorporates two of these, one bearing a mop and the other a broom, that meander about inside
      a steel frame.

      Kuku Yalanji/Kalkadoon artist Kim Ah Sam’s collection of woven sculptures Our Country are also mobile, although they
      don’t keep the floor clean: made of repurposed materials such as old bamboo blinds, they hover and spin in the air.

      The works are inspired by termite mounds and mountains,
      and each one is the product of hours of weaving and many sleepless nights,
      the artist explained.

      Our Country is installed not far from an artwork that could
      not be more different – a bedazzled, LED-lit hearse titled F*** Me Dead, by artist Paul Yore.

      “It used to belong to a funeral home. I found it online, actually – I’m an avid collector of things,”
      Yore told reporters.

      New works by well-known artists were also on show at the fair’s gallery booths, with dozens of paintings and prints by John Wolseley at Australian Galleries, inspired by
      the return of endangered animals to the Northern Territory.

      At Roslyn Oxley9 Gallery there’s the latest series of large scale photographs from Tracey Moffat titled The Burning, frontier landscapes that
      form the setting for one of Moffat’s mysterious dramas,
      played out in a series of stills.

      Meanwhile at Ames Yavuz, Reko Rennie – whose retrospective
      at the NGV finished up in January – shows off a
      recent move into figurative painting.

      One standout booth is the Australian Tapestry
      Workshop, where collaborations with artists including Atong Atem and Janet Laurence are on show, and
      visitors can get a peek at vibrant samples from a major four-by-10-metre weaving project
      for the Footscray Hospital, due to be installed later in the year.

      Possibly the most expensive work for sale is
      a $US200,000 ($A310,000) four-screen video work by
      the international art collective teamLab, on show at Sydney’s Martin Browne Contemporary.

      Whoever buys this will almost certainly be allowed into the Fair’s VIP lounge, which is sectioned off using inflatable flesh-coloured walls –
      worth seeing, even if you can’t get inside.

      At MARS Gallery, Kenny Pittock continues his long-running series of shopping lists, from
      the tiniest scrap of paper rendered in ceramics, to a large scale aluminium version that reads “peas, bread cream, my red wine.”

      The galleries will be hoping Melbourne’s art lovers will add some works of
      art to their shopping lists too.

      Melbourne Art Fair runs until Sunday.

    • April 10, 2025 at 5:01 pm
      Permalink

      Hey I know this is off topic but I was wondering if
      you knew of any widgets I could add to my blog that automatically
      tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time
      and was hoping maybe you would have some experience with something
      like this. Please let me know if you run into anything.
      I truly enjoy reading your blog and I look forward to your new updates.

    • April 10, 2025 at 9:56 pm
      Permalink

      This paragraph will help the internet viewers
      for creating new weblog or even a weblog from start to end.

    • April 11, 2025 at 7:04 am
      Permalink

      Thanks for your personal marvelous posting!
      I actually enjoyed reading it, you may be a great author.I will be sure to bookmark your blog and definitely will
      come back later in life. I want to encourage you continue your great writing,
      have a nice afternoon!

    • April 14, 2025 at 2:36 am
      Permalink

      Just wish to say your article is as amazing.

      The clarity to your post is just excellent and i can assume you are an expert on this subject.
      Fine along with your permission let me to grab your RSS
      feed to stay up to date with drawing close post.
      Thank you 1,000,000 and please carry on the gratifying work.

    • April 14, 2025 at 12:09 pm
      Permalink

      The word “Phim Le” translates to “Movies” or “Film” it originates fro Vietnam.

      There are many websites for watching “Phim Le” online, some of
      them are: “film4vn”, “thegiofilm”, “vuilen”, “onlinephim”,
      “noiket” to mention a few.

    • April 15, 2025 at 12:30 am
      Permalink

      My brother recommended I may like this web site.
      He was once totally right. This put up truly made my day.
      You cann’t imagine just how so much time I had spent for this information! Thank you!

    • April 16, 2025 at 8:51 pm
      Permalink

      Pretty section of content. I just stumbled upon your blog and
      in accession capital to assert that I acquire actually enjoyed account your blog posts.

      Any way I’ll be subscribing to your feeds and even I achievement you access consistently fast.

    • April 18, 2025 at 12:10 pm
      Permalink

      Hey I know this is off topic but I was wondering if you
      knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
      I’ve been looking for a plug-in like this for quite some time and was hoping maybe you
      would have some experience with something like this.
      Please let me know if you run into anything. I truly enjoy reading your blog and
      I look forward to your new updates.

    • April 19, 2025 at 3:40 am
      Permalink

      Good article. I’m dealing with a few of these issues as well..

    • April 22, 2025 at 8:59 am
      Permalink

      At this time it looks like Drupal is the best blogging platform available right now.
      (from what I’ve read) Is that what you are using on your blog?

    • April 23, 2025 at 9:01 pm
      Permalink

      Thank you for the auspicious writeup. It in fact was a amusement account it.
      Look advanced to far added agreeable from you!
      However, how could we communicate?

    • April 24, 2025 at 12:11 pm
      Permalink

      Nice post. I used to be checking continuously this weblog and I’m inspired!
      Extremely useful info specially the closing phase :) I care for
      such info much. I was seeking this particular info for a very lengthy time.
      Thanks and best of luck.

    • April 25, 2025 at 11:46 am
      Permalink

      I don’t usually comment but I gotta say appreciate it for the post on this
      special one :D.

    • April 25, 2025 at 8:52 pm
      Permalink

      Greetings I am so excited I found your blog page, I really found you by mistake, while I was
      searching on Aol for something else, Anyways I am here now and would just like to say kudos for a incredible post and a
      all round thrilling blog (I also love the theme/design), I don’t have time to
      read it all at the moment but I have book-marked it and also
      included your RSS feeds, so when I have time I will be back to read much more, Please do keep
      up the fantastic job.

    • April 28, 2025 at 5:36 am
      Permalink

      Highly descriptive article, I liked that a lot. Will there be a part
      2?

    • April 28, 2025 at 1:24 pm
      Permalink

      I’m amazed, I have to admit. Seldom do I encounter a blog that’s both educative
      and engaging, and without a doubt, you’ve hit the nail on the head.
      The issue is an issue that not enough people are speaking intelligently about.
      I am very happy I came across this in my search for
      something concerning this.

    • April 29, 2025 at 1:17 am
      Permalink

      Good way of describing, and good article to get information concerning my presentation topic, which i am going to
      present in university.

    • May 11, 2025 at 8:43 pm
      Permalink

      Your mode of describing everything in this
      post is in fact pleasant, all can without difficulty understand
      it, Thanks a lot.

    • May 12, 2025 at 6:20 am
      Permalink

      certainly like your web-site however you need to take a look at the spelling on quite a few of your posts.
      A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality then again I’ll certainly come again again.

    • May 16, 2025 at 2:31 pm
      Permalink

      hey there and thank you for your info – I have definitely picked up something
      new from right here. I did however expertise a few technical issues
      using this web site, as I experienced to reload
      the web site a lot of times previous to I could get it to load correctly.
      I had been wondering if your web host is OK?
      Not that I’m complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage
      your high-quality score if ads and marketing with Adwords.
      Anyway I’m adding this RSS to my email and can look out for much more of your
      respective exciting content. Ensure that you update this again very soon.

    • May 17, 2025 at 10:11 pm
      Permalink

      Heya i’m for the first time here. I found this board and I find It truly useful & it helped
      me out much. I hope to give something back and help others like
      you helped me.

    • May 21, 2025 at 9:38 am
      Permalink

      Definitely believe that which you said. Your favorite reason seemed to be
      on the net the easiest thing to be aware of. I
      say to you, I definitely get irked while people think about worries
      that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing
      without having side effect , people can take a signal. Will probably
      be back to get more. Thanks

    • May 22, 2025 at 12:32 pm
      Permalink

      I constantly emailed this webpage post page to all my contacts,
      since if like to read it then my contacts will too.

    • May 23, 2025 at 12:27 pm
      Permalink

      You actually make it appear really easy with your presentation however I to find this matter to be really one thing that I
      think I’d by no means understand. It kind of feels too complicated
      and extremely vast for me. I am looking ahead in your next
      publish, I will try to get the dangle of it!

    • May 26, 2025 at 4:01 am
      Permalink

      What i don’t understood is in truth how you are no
      longer really a lot more smartly-favored than you might be right now.
      You are so intelligent. You know thus significantly when it comes to this
      matter, made me in my opinion believe it from numerous varied angles.
      Its like women and men aren’t fascinated until it is one thing to do with Girl gaga!
      Your individual stuffs excellent. Always handle it up!

    • May 26, 2025 at 10:07 am
      Permalink

      Hello! I’m at work surfing around your blog from my new
      apple iphone! Just wanted to say I love reading your blog and
      look forward to all your posts! Keep up the fantastic work!

    • May 27, 2025 at 5:32 am
      Permalink

      Thank you for the auspicious writeup. It in fact was once a enjoyment account it.
      Glance complicated to far added agreeable from you!
      By the way, how could we keep in touch?

    • May 27, 2025 at 10:15 am
      Permalink

      It’s hard to find educated people on this topic, however, you sound like you know what you’re talking about!
      Thanks

    • June 12, 2025 at 8:53 am
      Permalink

      Asking questions are really nice thing if you are not understanding something totally, except this post presents good understanding yet.

    • June 16, 2025 at 10:54 am
      Permalink

      What’s up, yup this piece of writing is genuinely pleasant and I have learned lot of things
      from it regarding blogging. thanks.

    • June 17, 2025 at 7:38 am
      Permalink

      I loved as much as you will receive carried out right here.
      The sketch is attractive, your authored subject matter stylish.
      nonetheless, you command get got an nervousness over that you wish be delivering the following.
      unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike.

    Leave a Reply

    Your email address will not be published. Required fields are marked *