Reputation: 111
I'm using ASP.NET MVC3 to create a blog and I want to create a tagCloud for it.
Now my question is how I get it into a list (do I need to?), count and then print it out in different sizes?
EDIT:
I have now able to count every tag in every post with following:
Dictionary<string, int> tagLista = new Dictionary<string, int>();
foreach (Post post in Model)
{
foreach (Tag tag in post.Tags)
{
if (!tagLista.ContainsKey(tag.Name))
{
tagLista[tag.Name] = 1;
}
else
{
tagLista[tag.Name] += 1;
}
}
}
//Print out diff. sizes depending on count
foreach (KeyValuePair<string, int> pair in tagLista)
{
if (pair.Value <= 2)
{
<a class="minSize" href="@Href("~/Posts/Tags/" + pair.Key)">@pair.Key</a>
}
if (pair.Value > 2 && pair.Value <= 4)
{
<a class="medSize" href="@Href("~/Posts/Tags/" + pair.Key)">@pair.Key</a>
}
if (pair.Value > 4 && pair.Value >= 6)
{
<a class="maxSize" href="@Href("~/Posts/Tags/" + pair.Key)">@pair.Key</a>
}
}
The problem here is now that it only shows the tags of all posts on the current page, and not all tags from the database. How should I do instead? On the top of this view(Index) I use:
@using Blog.Models;
@model IEnumerable<Post>
Thanks for any help!
Upvotes: 1
Views: 298
Reputation: 111
I have now able to count every tag in every post with following:
Dictionary<string, int> tagLista = new Dictionary<string, int>();
foreach (Post post in Model)
{
foreach (Tag tag in post.Tags)
{
if (!tagLista.ContainsKey(tag.Name))
{
tagLista[tag.Name] = 1;
}
else
{
tagLista[tag.Name] += 1;
}
}
}
//Print out diff. sizes depending on count
foreach (KeyValuePair<string, int> pair in tagLista)
{
if (pair.Value <= 2)
{
<a class="minSize" href="@Href("~/Posts/Tags/" + pair.Key)">@pair.Key</a>
}
if (pair.Value > 2 && pair.Value <= 4)
{
<a class="medSize" href="@Href("~/Posts/Tags/" + pair.Key)">@pair.Key</a>
}
if (pair.Value > 4 && pair.Value >= 6)
{
<a class="maxSize" href="@Href("~/Posts/Tags/" + pair.Key)">@pair.Key</a>
}
}
The problem here is now that it only shows the tags of all posts on the current page, and not all tags from the database. How should I do instead? On the top of this view(Index) I use:
@using Blog.Models;
@model IEnumerable<Post>
Thanks for any help!
Upvotes: 1
Reputation: 32758
You can try this jquery plugin. Basically you should group all the posts based on tags.
<div id="tagCloud">
foreach(var tag in Tags)
{
<a href="@tag.Path()" rel="@tag.Posts.Count">@tag.Name</a>
}
</div>
$.fn.tagcloud.defaults = {
size: {start: 14, end: 18, unit: 'pt'},
color: {start: '#cde', end: '#f52'}
};
$(function () {
$('#tagCloud a').tagcloud();
});
Upvotes: 0
Reputation: 4974
I couldn't test this but I hope this works anyways:
var list = Model.SelectMany(x => x.Tags).GroupBy(x => x.Name, g => new {Name = g.Key, Amount = g.Count()});
returns a list with Tag Names and their respective amounts.
Upvotes: 0