这个问题在这里已有答案:
我试图生成一个部分视图,允许我在主页(索引)上显示最近的上下文。但是,模型仅返回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");
按照惯例,@await Html.PartialAsync("_RecentPodcasts")
剃刀知道如何找到它。现在,为了传递数据,你需要有某种方法来实际获取数据吗?
public async Task<IActionResult> _RecentPodcasts()
殴打应该用于命名该方法(提示下降_
)。实际上惊讶编译器没有抱怨。
Home / Index.cshtml将有一个viewmodel,它将具有类型的属性......你猜对了..“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 )
应该只是覆盖它...其余的空白和...将在你的.net核心/ mvc之旅中发现