I have a view showing all posts in the database. And I need to create a partial view that contains the top 5 highest viewed posts.
Here is my PostController controller:
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 GetMostViewedPost()
{
var result = uow._post.GetMostViewedPost(5).ToList();
ViewBag.MostViewedPost = result;
return PartialView(result);
}
}
My Partial view:
<h3>Most Viewed Posts</h3>
@foreach (var post in ViewBag)
{
<!-- Post preview-->
<div class="post-preview">
<h4 class="post-title">@post.Title</h4>
<h5 class="post-subtitle" style="font-weight:200">@post.ShortDescription</h5>
<p class="post-meta">
Posted on @post.PostedOn
</p>
</div>
}
I'm using ViewBag to pass the data into Partial View. I tried some (dumb) ways, and they didn't work. Please guide me, and if anything is wrong with my code, help me to fix that.
Try to change your code as follows: Create a class for the result:
Change your action method :
In your
index.cshtmlfile add following lines(replace ... by your code):You don't need
GetMostViewedPostaction method anymore.And change partial view as follows: