我在显示数据库中最受欢迎的标签时遇到问题。我不确定这个问题的标题,所以如果有人有更好的标题,请重命名。
场景
我需要在我的索引页面上显示最近的帖子、最近的画廊和最流行的标签。我决定为此使用元组,在我尝试显示最受欢迎的标签之前,它工作正常。
错误
The model item passed into the dictionary is of type 'System.Tuple
3[photoBlog.Models.Gallery[],photoBlog.Models.Post[],System.Linq.IGrouping2[System.Int32,photoBlog.Models.PostTag][]]', but this dictionary requires a model item of type 'System.Tuple`3[photoBlog.Models.Gallery[],photoBlog.Models.Post[],photoBlog.Models.PostTag[]]'.
如您所见,它给我的 View 提供了错误的对象类型。我希望它是一个数组,但它给了我某种 System.Linq.Grouping 项。
代码
如您所见,我在我的 Controller 中将其转换为数组。
public ActionResult Index()
{
photoBlogModelDataContext _db = new photoBlogModelDataContext();
var posts = _db.Posts.OrderByDescending(x => x.DateTime).Take(4).ToArray();
var galleries = _db.Galleries.OrderByDescending(x => x.ID).Take(4).ToArray();
var posttags = _db.PostTags.GroupBy(x => x.TagID).OrderBy(x => x.Count()).Take(4).ToArray();
return View(Tuple.Create(galleries, posts, posttags));
}
我的观点是直截了当的,请注意,在我尝试添加最流行的标签之前,这确实有效。
@model Tuple<photoBlog.Models.Gallery[], photoBlog.Models.Post[], photoBlog.Models.PostTag[]>
@foreach (var tag in Model.Item3)
{
@tag.Tag.Name
}
请您参考如下方法:
你可能想要
var posttags = _db.PostTags
.GroupBy(x => x.TagID)
.OrderBy(x => x.Count())
// Take each group and pass the first tag of the group
.Select(g => g.First())
.Take(4)
.ToArray();
此刻你正在经过,例如最受欢迎标签的所有 8 个实例,第二受欢迎标签的所有 5 个实例,等等,每个实例都在自己的组中。我想您只是想传递每个标签的“示例”。
