[英]Displaying results from LINQ query in ASP.NET MVC
我有一個包含LINQ查詢的控制器。 我的查詢類似於以下內容:
var posts = GetBlogPosts();
var results = from post in posts
select new
{
Title = "This is the blog title",
Url = "www.google.com",
Author = "Bill Jones",
AuthorUrl = "www.billjones.com",
Description = "This is the description of the post"
};
ViewBag.Posts = results;
我想在我的視圖中顯示帖子。 目前,我有以下內容:
@foreach (var post in ViewBag.Posts)
{
<div class="postBody">
<h1 class="blogTitle">@post.Title</h1>
<p class="blogInfo">@post.Description</p>
</div>
}
當我執行此操作時,我在運行時收到錯誤。 我的錯誤說:
'object' does not contain a definition for 'Title'
我究竟做錯了什么?
那是因為你的代碼的這一部分正在選擇一個匿名對象。 視圖不知道是什么類型的對象。 您的Viewbag也是一個動態對象,不會告訴視圖對象中有哪種特定類型的對象。
select new
{
Title = "This is the blog title",
Url = "www.google.com",
Author = "Bill Jones",
AuthorUrl = "www.billjones.com",
Description = "This is the description of the post"
};
您很可能可以執行以下操作
ViewBag.Posts = GetBlogPosts();
在您的視圖中,您將執行此操作:
@foreach (var post in (IEnumerable<Post>)ViewBag.Posts)
{
<div class="postBody">
<h1 class="blogTitle">@post.Title</h1>
<p class="blogInfo">@post.Description</p>
</div>
}
或者更好的是通過將以下內容放在頁面頂部來創建強類型視圖
@model IEnumerable<Post>
在您的控制器中,您返回View(GetBlogPosts());
在你看來,你做到了
@foreach (var post in Model)
{
<div class="postBody">
<h1 class="blogTitle">@post.Title</h1>
<p class="blogInfo">@post.Description</p>
</div>
}
您可以使用部分視圖而不是使用ViewBag,因為ViewBag。 您需要在控制器中創建新的Action,然后使用HTML.RenderAction從Parent視圖調用該操作,如下所示:1- Create New Action以包含Linq代碼
[ChildActionOnly]
public ViewResult GetPosts()
{
var posts = GetBlogPosts();
var results = from post in posts
select new
{
Title = "This is the blog title",
Url = "www.google.com",
Author = "Bill Jones",
AuthorUrl = "www.billjones.com",
Description = "This is the description of the post"
};
return PartialView("ViewName,posts); // the partial view name ,with posts object
}
2-現在創建一個具有(Posts)類型的強類型視圖的部分視圖,並為其指定任何名稱,然后像稍微更改一樣編寫代碼。
@model IEnumerable<Post>
@foreach (var post in Model)
{
<div class="postBody">
<h1 class="blogTitle">@post.Title</h1>
<p class="blogInfo">@post.Description</p>
</div>
}
3-現在在父視圖中添加HTML.RenderAction屁股
<html>
<head>/<head>
<body>
...
<div>
@ { Html.RenderAction("GetPosts"); } <!--ActionName -->
</div>
...
</body>
</html>
有關更多信息,請查看以下鏈接
ChildActionExtensions.RenderAction方法
RenderPartial vs RenderAction vs MVC Razor中的Partial vs Action
我希望有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.