0

I am trying to generate a partial view that will allow me to display recent context on the home page (Index). However, the model is only returning as NULL.

Podcast controller method:

// Generates list of most recent 2 podcasts
public async Task<IActionResult> _RecentPodcasts()
{
        var recentList = from p in _context.Podcast
                         select p;
        recentList = recentList.OrderByDescending(p => p.PublishDate).Take(2);            

        return View(await recentList.ToListAsync());
}

Partial view (Podcasts/_RecentPodcasts.cshtml)

@model IEnumerable<ComesNaturally.Models.Podcast>

@{ 
    ViewData["Title"] = "_RecentPodcasts";
}


<div class="col-md-6">
<div class="table-title">
    <table class="table-fill">
        <thead>
            <tr>
                <th>Recent Podcasts</th>
            </tr>
        </thead>
@if (Model == null)
{
        <tr> No items found</tr>}
else
{
    @foreach (var item in Model)
     { 
         <tr>
             <td><a asp-action="Details" asp-route-id="@item.ID" class="alert-link">@Html.DisplayFor(modelItem => item.Title)</a></td>
         </tr>
     }}
    </table>
</div>
</div>

Main view (Home/Index.cshtml)

@Html.Partial("~/Views/Podcasts/_RecentPodcasts.cshtml");
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Is the model in your main view the same as the one in your partial view? If not have your tried passing the model as a parameter to the partial view in the `Partial` statement? (or is it an expression?) – Gilles Dec 22 '17 at 19:55

1 Answers1

0

@await Html.PartialAsync("_RecentPodcasts") razor knows how to find it, by convention. Now as for passing the data you need to have some sort of means to actually get the data right?

public async Task<IActionResult> _RecentPodcasts() beatings shall be doled out for the naming of that METHOD (hint drop the _). Actually surprised the compiler didn't complain.

Home / Index.cshtml will have a viewmodel which will have a property of type... you guessed it.. "RecentPodCasts"

//fill it from HomeController...
public class HomeViewModel(){
    public IEnumerable<Podcast> RecentPodcasts {get;set;}
}

//HomeController.cs
public async Task<IActionResult> Index(){
     var vm = new HomeViewModel();
     vm.RecentPodcasts = await _context.Podcasts.OrderByDescending(p => p.PublishDate).Take(2).ToListAsync();

     return View(vm);
}


//home/index.cshtml
@model YourNameSpace.Models.HomeViewModel  


@*somewhere in Home/Index.cshtml*@
@await Html.PartialAsync("_RecentPodCasts", Model.RecentPodcasts )

that should just about cover it... The rest of the blanks and ...'s will be for you discover on your .net core/ mvc journey

mvermef
  • 3,814
  • 1
  • 23
  • 36