显示局部视图MVC三个随机文章 [英] display three random articles in a partial view mvc
问题描述
我有一个博客,其中的某个网页MainDetails,我在这里显示当前的博客,这里面详细介绍我显示页面 partialview
并在这部分我试图显示多达三个随机
类似的帖子。不过我升技坚持的语法:
I have a blog in which one of the pages is MainDetails, here I display the current blog, inside this details page I display a partialview
and in that partial I am trying to display three random
similar posts. However I am abit stuck with the syntax:
在我的局部视图所有我做我的列表中显示的帖子,但是我想只显示3相关的类别属性的职位,但随机
。 发表
有属性的CategoryId
,发表
有许多人同类别一对一的关系(类别可以有很多帖子,但后期只能有一类),我试图让按类别相关的3偶合的帖子:
In my partial view all I am doing is displaying the posts in my list, however I want to display only 3 posts related to the Category property, but at random
. Post
has the property CategoryId
, Post
has a many to one relationship with Category (category can have many posts but post can only have one category), I am trying to get 3 randoms posts related by category:
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项:
However the output on my maindetails
page for the above action and partialview
is still showing more than 3 items:
推荐答案
如果你只是想有3个随机的文章,你可以使用类似这样
If you just want to have 3 random articles you could use something like this
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);
}
}
和您的视图中,你会用以下称之为
And inside your view you would call it with the following
@Html.Action("RandomPosts", "Home", new { categoryId = 1 })
这篇关于显示局部视图MVC三个随机文章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!