如何在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 thedb.Postsquery. 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
PostViewModelstays 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
相关产品推荐
相关产品推荐

