用taglink创建标签云?

时间:2012-09-23 17:15:43

标签: asp.net asp.net-mvc asp.net-mvc-3 tag-cloud

我正在使用ASP.NET MVC3创建一个博客,我想为它创建一个tagCloud。

现在我的问题是如何将它放入列表中(我需要吗?),计数然后以不同的尺寸打印出来?

编辑:

我现在能够计算每个帖子中的每个标签:

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> 
        }
    }

现在的问题是它只显示当前页面上所有帖子的标签,而不是数据库中的所有标签。我该怎么做?在这个视图(索引)的顶部我使用:

@using Blog.Models;
@model IEnumerable<Post>

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

我现在能够计算每个帖子中的每个标签:

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> 
    }
}

现在的问题是它只显示当前页面上所有帖子的标签,而不是数据库中的所有标签。我该怎么做?在这个视图(索引)的顶部我使用:

@using Blog.Models;
@model IEnumerable<Post>

感谢您的帮助!

答案 1 :(得分:0)

我无法测试这个,但我希望无论如何都可以:

var list = Model.SelectMany(x => x.Tags).GroupBy(x => x.Name, g => new {Name = g.Key, Amount = g.Count()});

返回一个包含标签名称及其各自金额的列表。

答案 2 :(得分:0)

您可以尝试使用this jquery插件。基本上你应该根据标签对所有帖子进行分组。

<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();
});