[英]display three random articles in a partial view mvc
我有一個博客,其中一個頁面是MainDetails,在這里我顯示當前的博客,在這個詳細信息頁面中我顯示了一個部分partialview
,在那部分我試圖顯示三個random
相似的帖子。 但是我堅持使用語法:
在我的部分視圖中,我所做的只是顯示列表中的帖子,但是我想只顯示與Category屬性相關的3個帖子,但是random
。 Post
有屬性CategoryId
, Post
與Category有多對一的關系(類別可以有很多帖子,但帖子只能有一個類別),我想獲得3個類別相關的randoms帖子:
PostController GetSimilarPosts動作:
public ActionResult GetSimilarPosts(int id = 0)
{
var randomPosts = db.Categories.Where(p => p.Id == id).SelectMany(p => p.Posts).OrderBy(r => Guid.NewGuid()).Take(3);
return View(randomPosts.ToList());
}
但是,我的maindetails
頁面上的上述操作和部分partialview
的輸出仍然顯示超過3個項目:
如果你只想要3篇隨機文章,你可以使用這樣的東西
public class HomeController : Controller
{
private DatabaseContext db = new DatabaseContext();
public ActionResult RandomPosts(int categoryId)
{
var randomPosts = db.Posts.Where(x => x.CategoryId == categoryId)
.OrderBy(r => Guid.NewGuid()).Take(3);
return View(randomPosts);
}
}
在您的視圖中,您可以使用以下內容調用它
@Html.Action("RandomPosts", "Home", new { categoryId = 1 })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.