我相信這是相對簡單的,我只是一直跑進磚牆。我有兩個實體類設置像這樣:在MVC視圖中獲取ViewModel數據
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime CreatedDate { get; set; }
public string Content { get; set; }
public string Tags { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int Id { get; set; }
public string DisplayName { get; set; }
public string Email { get; set; }
public DateTime DateCreated { get; set; }
public string Content { get; set; }
public int PostId { get; set; }
public Post Post { get; set; }
}
我建立了我的視圖模型是這樣的:
public class PostCommentViewModel
{
public Post Post { get; set; }
public IQueryable<Comment> Comment { get; set; }
public PostCommentViewModel(int postId)
{
var db = new BlogContext();
Post = db.Posts.First(x => x.Id == postId);
Comment = db.Comments;
}
}
我有我的控制器這樣做:
public ActionResult Details(int id = 0)
{
var viewModel = new PostCommentViewModel(id);
return View(viewModel);
}
然後該視圖看起來像這樣:
@model CodeFirstBlog.ViewModels.PostCommentViewModel
<fieldset>
<legend>PostCommentViewModel</legend>
@Html.DisplayFor(x => x.Post.Title)
<br />
@Html.DisplayFor(x => x.Post.Content)
<br />
@Html.DisplayFor(x => x.Post.CreatedDate)
<hr />
@Html.DisplayFor(x => x.Comment)
</fieldset>
結果是顯示數據,但不是我想要的評論。
你看到的評論(有兩個),只是顯示在每一個「12」
我怎樣才能得到它進入並顯示評論細節id屬性具體到這個特定的職位?我想象一個foreach循環的順序,但我不知道如何正確鑽入Model.Comment屬性。
我嘗試這樣做:
@foreach(var item in Model.Comment)
{
@Html.DisplayFor(item.DisplayName)
@Html.DisplayFor(item.Content)
@Html.DisplayFor(item.DateCreated)
}
但我得到的錯誤是「類型參數的方法「System.Web.Mvc.Html.DisplayExtensions.DisplayFor(System.Web.Mvc.HtmlHelper,系統。 Linq.Expressions.Expression>)'不能根據用法推斷,請嘗試明確指定類型參數。「
不知道什麼,我該怎麼辦這裏..
你不需要comment.content嗎? – christiandev
這工作。如果我想要我的內容,我只需要做(x => comment.Content) – ledgeJumper