简体   繁体   中英

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. 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 . 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 Action:

    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:

在此输入图像描述

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 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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