试图仅从列表中的一个类别中获取可单击单个 post 的文章?
Trying to get only articles from one category in a list that is clickable to a single post?
我是 MVC 的新手,我正在创建一个博客类型的网站。我正在尝试在我的视图页面中创建一个列表,其中仅包含一个类别的所有 post。我使用的代码显示了所有 posts。我只想显示 CategoryType 4 中的 posts。非常感谢任何帮助。我已经搜索了很多,现在正在拔头发。这是我的代码。
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 过滤 post 的列表。
您可以在 select 使用如下内容后使用 LinQ 执行此操作:
List<PostViewModel> postVMList = postlist.Select(x => new
PostViewModel
{
CategoryType = x.CategoryType,
PostId = x.PostId,
PostName = x.PostName
}).Where(post => post.CategoryType == 4).ToList();
希望对您有所帮助!
我是 MVC 的新手,我正在创建一个博客类型的网站。我正在尝试在我的视图页面中创建一个列表,其中仅包含一个类别的所有 post。我使用的代码显示了所有 posts。我只想显示 CategoryType 4 中的 posts。非常感谢任何帮助。我已经搜索了很多,现在正在拔头发。这是我的代码。
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 过滤 post 的列表。
您可以在 select 使用如下内容后使用 LinQ 执行此操作:
List<PostViewModel> postVMList = postlist.Select(x => new
PostViewModel
{
CategoryType = x.CategoryType,
PostId = x.PostId,
PostName = x.PostName
}).Where(post => post.CategoryType == 4).ToList();
希望对您有所帮助!