title: How can I call a controller action when rendering a partial view?
body: <p>I am creating a partial view for a sidebar that will show the most popular posts in my site. How can I create a separated controller for loading the model required by the partial view? (The <code>IEnumerable&lt;Post&gt;</code> with the popular posts)</p>
  
  <p>Currently I have created a controller class that loads the popular posts but I keep getting errors when rendering the partial as I cannot call the controller and load the partial model. For example, if I call it from a view where I render a single post, the model types won't match (<code>Post</code> vs <code>IEnumerable&lt;Post&gt;</code>)</p>
  
  <p>This is my <code>SidebarController</code>:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.EntityFrameworkCore;
  using GoBaron.Front.Models;
  
  namespace GoBaron.Front.Controllers
  {
      public class SidebarController : Controller
      {
          private readonly ApplicationDbContext _context;
  
          public SidebarController(ApplicationDbContext context)
          {
              _context = context;
          }
  
          public async Task&lt;IActionResult&gt; PopularPosts()
          {
              return PartialView(await _context.Posts
                  .Where(p =&gt; p.IsActive == true)
                  .OrderByDescending(p =&gt; p.Id)
                  .Take(5)
                  .ToListAsync());
          }
      }
  }
  </code></pre>
  
  <p>And this is my partial view <code>PopularPosts.cshtml</code>:</p>
  
  <pre><code>@model IEnumerable&lt;GoBaron.Front.Models.Post&gt;
  @using GoBaron.Front.Data.Extensions
  
  @if (Model.Any())
  {
      &lt;div class="sidebar-item" id="topTrending"&gt;
          &lt;header class="sidebar-item__header"&gt;
              &lt;h1&gt;Najpopularniejsze&lt;/h1&gt;
          &lt;/header&gt;
          &lt;div class="sidebar-item__content"&gt;
              @foreach (var item in Model)
              {
                  &lt;a asp-controller="Post" asp-action="Details" asp-route-id="@item.Id" asp-route-slug="@item.Title.ConvertToSlug()" title="@item.Title"&gt;
                      &lt;div class="sidebar-post-item" style="background-image:url('@item.PosterUrl')"&gt;
                          &lt;span class="sidebar-post-item__counter"&gt;+5&lt;/span&gt;
                          &lt;span class="sidebar-post-item__title"&gt;@item.Title&lt;/span&gt;
                      &lt;/div&gt;
                  &lt;/a&gt;
              }
          &lt;/div&gt;
      &lt;/div&gt;
  }
  </code></pre>
  
  <p>When I want to include the popular posts sidebar, for example in the layout, I just add:</p>
  
  <pre><code>@await Html.PartialAsync("~/Views/Sidebar/PopularPosts.cshtml")
  </code></pre>