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
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:
Create Tag table and bind it to Event.
Update your Entity Framework model to reflect new changes made to database.
Add some classes that hold tag cloud data (TagCloud is container class that keeps collection of MenuTag objects).
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.
Excellent post! :)
You can return MvcHtmlString instead of string to avoid using Html.Raw()
Slawek, what’s the difference? This way or other we have to write too much :)
Great article. One question – can you share how you are handling the insertion of the events and tags into the respective tables?
Showjumper, take a look at this solution: https://gunnarpeipman.com/aspnet/asp-net-mvc-implementing-checkboxlist/
Pingback:ASP.NET MVC: Implementing CheckBoxList | Gunnar Peipman - Programming Blog
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!!
Quality content is the secret to invite the users to pay a visit
the website, that’s what this website is providing.
It’s not my first time to visit this website, i am browsing
this website dailly and get pleasant data from here daily.
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..
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?
Inspiring story there. What occurred after? Good luck!
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?
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.
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.
This paragraph will help the internet viewers
for creating new weblog or even a weblog from start to end.
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!
https://jekyll.s3.us-east-005.backblazeb2.com/20241129-3/research/je-tall-sf-marketing-(404).html
It’s your duty to understand what she wants from both you and the groom’s mom in phrases of your apparel.
Mighty Dog Roofing
8110 East 126th St S
Bixby, OⲔ 74008, United Stɑtes
19182125646
reliable home exterior improvements
If you are going for best contents like myself, simply visit this web site everyday
since it offers quality contents, thanks
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.
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.
YU
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!
If you want to increase your experience only keep visiting
this web page and be updated with the most up-to-date news posted here.
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.
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.
Good article. I’m dealing with a few of these issues as well..
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?
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?
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.
I don’t usually comment but I gotta say appreciate it for the post on this
special one :D.
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.
Highly descriptive article, I liked that a lot. Will there be a part
2?
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.
Good way of describing, and good article to get information concerning my presentation topic, which i am going to
present in university.
This piece of writing is really a good one it helps new the web people, who are wishing in favor of blogging.
Your mode of describing everything in this
post is in fact pleasant, all can without difficulty understand
it, Thanks a lot.
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.
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.
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.
I need to to thank you for this great read!!
I absolutely enjoyed every bit of it. I have got you book-marked
to look at new stuff you post…
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
I constantly emailed this webpage post page to all my contacts,
since if like to read it then my contacts will too.
This is my first time visit at here and i am really pleassant to read
all at one place.
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!
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!
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!
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?
It’s hard to find educated people on this topic, however, you sound like you know what you’re talking about!
Thanks
Asking questions are really nice thing if you are not understanding something totally, except this post presents good understanding yet.
What’s up, yup this piece of writing is genuinely pleasant and I have learned lot of things
from it regarding blogging. thanks.
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.