I have a Index view showing all posts in my database. And I want to create a partial view that displays 5 most viewed posts.
Here is my PostController :
public class PostController : Controller
{
private readonly IUnitOfWork uow;
public PostController(IUnitOfWork uow)
{
this.uow = uow;
}
public IActionResult Index()
{
var result = uow._post.GetAll().ToList();
return View(result);
}
public IActionResult Details(int id)
{
var post = uow._post.Find(id);
return View(post);
}
public IActionResult GetMostViewedPost()
{
var result = uow._post.GetMostViewedPost(5).ToList();
return PartialView(result);
}
}
The Index.cshtml:
@using FA.JustBlog.Core.Models;
@model IList<Post>;
<div class="row gx-4 g-lg-5 justify-content-center">
<div class="col-md-9 mx-auto">
<!-- Post preview-->
@foreach(var item in Model)
{
<div class="post-preview">
<a href="@Url.Action("Details", "Post", new {id = item.Id })">
<h2 class="post-title">@item.Title</h2>
<h3 class="post-subtitle">@item.ShortDescription</h3>
</a>
<p class="post-meta">
Posted by
<a href="@Url.Action("Details", "Post", new {id = item.Id })">JustBlog</a>
on @item.PostedOn
</p>
</div>
<!-- Divider-->
<hr class="my-4" />
}
<!-- Pager-->
<div class="d-flex justify-content-end mb-4"><a class="btn btn-primary text-uppercase" href="#!">Older Posts →</a></div>
</div>
</div>
How can I complete the code for partial view with ViewBag? Help me out! Thanks!
This should get you close.
First, create the partial view file _MostViewedPosts.cshtml and add the following code:
Then, modify the Index action in your PostController to fetch the 5 most viewed posts and pass them to the partial view using the ViewBag:
Finally, in your Index.cshtml file, add the partial view using Html.Partial() method: