简体   繁体   English

在局部视图mvc中显示三篇随机文章

[英]display three random articles in a partial view mvc

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. 我有一个博客,其中一个页面是MainDetails,在这里我显示当前的博客,在这个详细信息页面中我显示了一个部分partialview ,在那部分我试图显示三个random相似的帖子。 However I am abit stuck with the syntax: 但是我坚持使用语法:

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 . 在我的部分视图中,我所做的只是显示列表中的帖子,但是我想只显示与Category属性相关的3个帖子,但是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: Post有属性CategoryIdPost与Category有多对一的关系(类别可以有很多帖子,但帖子只能有一个类别),我想获得3个类别相关的randoms帖子:

PostController GetSimilarPosts Action: 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());
    }

However the output on my maindetails page for the above action and partialview is still showing more than 3 items: 但是,我的maindetails页面上的上述操作和部分partialview的输出仍然显示超过3个项目:

在此输入图像描述

If you just want to have 3 random articles you could use something like this 如果你只想要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);
     }
}

And inside your view you would call it with the following 在您的视图中,您可以使用以下内容调用它

@Html.Action("RandomPosts", "Home", new { categoryId = 1 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM