一如往常我會寫包含我想顯示,從來沒有像你那樣發送匿名對象到您的視圖中的信息這一觀點視圖模型啓動碼。
讓我們假設你想要顯示一個評論列表,併爲每個評論列出相應的評論。所以你的視圖模型看起來可能沿着這些線路:
public class ReviewViewModel
{
public int ReviewId { get; set; }
public string ReviewBody { get; set; }
public string ReviewHeadLine { get; set; }
public IList<CommentViewModel> Comments { get; set; }
}
public class CommentViewModel
{
public string CommentBody { get; set; }
}
這個定義,你可以執行你的LINQ查詢,提取必要的數據和項目,這個視圖模型:
IEnumerable<ReviewViewModel> viewModel =
from review in db.reviews
join comment in db.Comments
on review.ReviewId equals comment.ReviewId into joinedReviewComment
select new ReviewViewModel // <-- Always project to a view model and never to an anonymous object
{
review.ReviewBody,
review.ReviewHeadLine,
Comments = joinedReviewComment.Select(c => new CommentViewModel
{
CommentBody = c.CommentBody,
}).ToList(),
};
return View(viewModel.ToList()); // <-- Always pass a view model to your view
而現在所有這左邊是顯示在你的強類型查看此信息:
@model IList<ReviewViewModel>
<table>
<thead>
<tr>
<th>Review id</th>
<th>Review body</th>
<th>Review headline</th>
<th>Review comments</th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(x => x[i].ReviewId)</td>
<td>@Html.DisplayFor(x => x[i].ReviewBody)</td>
<td>@Html.DisplayFor(x => x[i].ReviewHeadLine)</td>
<td>
@for (var j = 0; j < Model[i].Comments.Count; j++)
{
<div>
@Html.DisplayFor(x => x[i].Comments[j].CommentBody)
</div>
}
</td>
</tr>
}
</tbody>
</table>
話雖如此突出的是一回事,但過濾你的數據是另一回事。假設您有數百萬條評論,每條評論都有數百萬條評論。進行上述查詢將簡單地使您的服務器停機。因此,在設計應用程序和視圖時應考慮這一點。不要猶豫,使用Where,Skip和Take操作符將結果集過濾爲一組有意義的數據集合,這些數據足夠合理,可以在單個視圖中顯示。
您的'select new {...}'創建了一個匿名對象集合(不是'Review'對象集合)。你需要用你想要的屬性(例如'ReviewVM')創建一個視圖模型,並使用'選擇新的ReviewVM {....}'(並將視圖中的模型更改爲'model IEnumerable' –
看左外層加入以下網頁:https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b#content – jdweng