显示另一个控制器的部分视图

时间:2017-12-22 19:07:55

标签: .net asp.net-mvc asp.net-core-mvc

我正在尝试生成一个部分视图,允许我在主页(索引)上显示最近的上下文。但是,模型仅返回NULL。

播客控制器方法:

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

部分视图(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>

主视图(Home / Index.cshtml)

@Html.Partial("~/Views/Podcasts/_RecentPodcasts.cshtml");

1 个答案:

答案 0 :(得分:0)

按惯例,

@await Html.PartialAsync("_RecentPodcasts") razor知道如何找到它。现在,为了传递数据,您需要采用某种方法来实际获取数据吗?

public async Task<IActionResult> _RecentPodcasts()殴打应该用于命名该方法(提示删除_)。实际上,编译器没有抱怨,感到很惊讶。

Home / Index.cshtml将有一个viewmodel,它将具有类型的属性......你猜对了..&#34; RecentPodCasts&#34;

//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 )

应该只是覆盖它...其余的空白和...将在你的.net核心/ mvc之旅中发现