Search code examples
asp.netmodel-view-controllercategoriesblogs

Trying to get only articles from one category in a list that is clickable to a single post?


I am new to MVC and I am creating a blog type website. I am trying to create a list in my view page of all post from just one category. The code I am using is showing all posts. I just want to show posts from CategoryType 4. I would really appreciate any help. I have searched so much and I am now pulling my hair out. Here is my code.

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);
    }
}

Solution

  • If I understood your problem correctly sounds like all you have to do is filter the list for post with CategoryType4.

    You can do that with LinQ after the select use something like this:

                List<PostViewModel> postVMList = postlist.Select(x => new
        PostViewModel
                {
                    CategoryType = x.CategoryType,
                    PostId = x.PostId,
                    PostName = x.PostName
    
                }).Where(post => post.CategoryType == 4).ToList();
    

    Hope this helps!