You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MVC博客中仅展示CategoryType 4的可点击文章列表?

Fix: Display Only Posts with CategoryType = 4 in MVC

Hey there! I see you're new to MVC and trying to filter your blog posts to only show those with CategoryType = 4—let's get this sorted out for you.

The root issue in your current code is that you're fetching all posts from the database with db.Posts.ToList() without adding a filter. We just need to add a Where clause to narrow down the results to the category you want.

Modified Index Action Method

Here's how your updated Index method should look:

public class PostController : Controller { 
    // GET: Post 
    public ActionResult Index() { 
        OnlineConciegerDBEntities db = new OnlineConciegerDBEntities(); 
        // Add the Where clause to filter for CategoryType = 4
        List<Post> postlist = db.Posts.Where(x => x.CategoryType == 4).ToList(); 
        List<PostViewModel> postVMList = postlist.Select(x => new PostViewModel { 
            CategoryType = x.CategoryType, 
            PostId = x.PostId, 
            PostName = x.PostName 
        }).ToList(); 
        return View(postVMList); 
    } 

    // Your existing PostDetail method remains the same
    public ActionResult PostDetail(int Postid) { 
        OnlineConciegerDBEntities db = new OnlineConciegerDBEntities(); 
        Post post = db.Posts.SingleOrDefault(x => x.PostId == Postid); 
        PostViewModel postVM = new PostViewModel(); 
        postVM.PostName = post.PostName; 
        postVM.PostContent = post.PostContent; 
        postVM.Keywords = post.Keywords; 
        return View(postVM); 
    } 
}

What Changed?

  • We added .Where(x => x.CategoryType == 4) right before .ToList() on the db.Posts query. This filters the posts at the database level (which is more efficient than fetching all posts and filtering them in memory).
  • The rest of your mapping to PostViewModel stays exactly the same—you'll just be working with a smaller, filtered list of posts.

Once you update this code, your view will only receive posts where CategoryType equals 4, so it'll display exactly the list you want.

内容的提问来源于stack exchange,提问作者Elizabeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:29:42