我是MVC的新手,我正在创建一个博客类型的网站。我想在一个类别的所有帖子的视图页面中创建一个列表。我正在使用的代码显示所有帖子。我只想展示CategoryType 4的帖子。我真的很感激任何帮助。我搜索了这么多,现在我把头发拉了出来。这是我的代码。
public class PostController : Controller
{
// GET: Post
public ActionResult Index()
{
OnlineConciegerDBEntities db = new OnlineConciegerDBEntities();
List<Post> postlist = db.Posts.ToList();
List<PostViewModel> postVMList = postlist.Select(x => new
PostViewModel
{
CategoryType = x.CategoryType,
PostId = x.PostId,
PostName = x.PostName
}).ToList();
return View(postVMList);
}
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);
}
}
如果我正确理解你的问题听起来就像你要做的就是用CategoryType4过滤帖子列表。
你可以选择使用这样的东西后用LinQ做到这一点:
List<PostViewModel> postVMList = postlist.Select(x => new
PostViewModel
{
CategoryType = x.CategoryType,
PostId = x.PostId,
PostName = x.PostName
}).Where(post => post.CategoryType == 4).ToList();
希望这可以帮助!