显示局部视图MVC三个随机文章 [英] display three random articles in a partial view mvc

查看:144
本文介绍了显示局部视图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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆