这必须非常简单,但我没有找到很多例子。我想获取所有带有相应标签的帖子并显示在视图中。基本上是一个简单的博客类型的东西。这是我的模型、视图模型、控制器和视图的代码。一切都可以减去标签,所以我的语法显然有问题。
public class MeWallPost
{
public virtual int MeWallPostId { get; set; }
public virtual string PostTitle { get; set; }
public virtual string PostContent { get; set;
public virtual DateTime PublishDate { get; set; }
public virtual ICollection<MeWallPostMeTag> MeWallPostMeTags { get; set; }
}
public class MeTag
{
public virtual int MeTagId { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<MeWallPostMeTag> MeWallPostMeTags { get; set; }
}
public class MeWallPostMeTag
{
[Key, Column(Order = 0)]
public virtual int MeWallPostId { get; set; }
[Key, Column(Order = 0)]
public virtual int MeTagId { get; set; }
public virtual MeWallPost MeWallPost { get; set; }
public virtual MeTag MeTag { get; set; }
}
----
public class MeWallPostViewModel
{
public string PostTitle { get; set; }
public string PostContent { get; set; }
public DateTime PublishDate { get; set; }
private IEnumerable<MeTag> _Tags = new List<MeTag>();
public IEnumerable<MeTag> Tags
{
get { return _Tags; }
set { _Tags = value; }
}
public IEnumerable<MeWallPostViewModel> GetPosts()
{
var db = new DatselleDB();
return from post in db.MeWallPosts
select new MeWallPostViewModel
{
PostTitle = post.PostTitle,
PostContent = post.PostContent,
PublishDate = post.PublishDate,
Tags = post.MeWallPostMeTags.Select(a => a.MeTag)
};
}
}
-----
public ViewResult Index()
{
return View(new MeWallPostViewModel());
}
------
@foreach (var item in Model.GetPosts()) {
<div class="postItem clear">
<h3>@Html.DisplayFor(modelitem => item.PostTitle)</h3>
<span class="date">@Html.DisplayFor(modelitem => item.PublishDate)</span>
<p>@Html.DisplayFor(modelItem => item.PostContent)</p>
@foreach (var tag in Model.Tags) {
@Html.DisplayFor(modelItem => tag.Name.ToString())
}
</div>
}