我有一个使用 Razor 和 Entity Framework 的 ASP.NET Core MVC 应用程序,我尝试在另一个(父)视图中包含一个(子)视图。
我发现的一个问题是他们使用不同的控制器。我按照有关在项目中使用和集成实体框架的 Microsoft 教程获得了子视图。
当我尝试启动应用程序时,它崩溃了,因为子视图中的模型为空(请参阅下面的简化代码)。到此阶段,Notes 控制器 -> Index 操作尚未命中,我想这是因为我的代码现在没有任何内容指向 Notes\Index。我不知道该怎么做。我知道即使对于不同的控制器,在另一个视图中包含视图也不是我第一个遇到的问题,但我发现的所有解决方案似乎都不适用于 ASP.NET Core,或者可能是我使用错误。
子视图(简化):
..\ProgMain\Views\Notes\Index.cshtml
@model IEnumerable<ProgMain.Models.NoteRecord>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Note)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) { // crash nullreferenceexception, Model is null
<tr>
<td>
@Html.DisplayFor(modelItem => item.Note)
etc.
对应控制器:
..\ProgMain\Controllers\NotesController.cs
namespace ProgMain.Controllers
{
public class NotesController : Controller
{
private readonly ApplicationDbContext _context;
public NotesController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index() // not hit
{
return _context.NotesSet != null
? View(await _context.NotesSet.ToListAsync())
: Problem("Entity set 'ApplicationDbContext.NotesSet' is null.");
}
etc
Notes
模型类:
..\ProgMain\Models\Notes.cs
namespace ProgMain.Models
{
public class NoteRecord
{
public Guid ID { get; set; }
public string? Note { get; set; }
public virtual List<NoteDetailRecord>? Details { get; set; }
}
etc.
}
家长视图:
..\ProgMain\Views\Home\Frontend.cshtml
@{
ViewData["Title"] = "Frontend"; // the upper entry in call stack, before crashed line
}
<div style="display:flex">
etc.
</div>
<partial name="/Views/Notes/Index.cshtml"></partial>