在另一个视图中使用视图

问题描述 投票:0回答:1

我有一个使用 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>
asp.net-core razor entity-framework-core asp.net-mvc-partialview
1个回答
0
投票

它崩溃是因为子视图中的模型为空(参见代码 如下,简化)。

在您提供的代码示例中,问题是由于子视图的模型为空引起的,因为子视图没有正确从父视图接收数据,在ASP.NET Core中,模型Tag Helper用于指定模型使用标签助手时传递给详细视图,如果标签中没有指定模型属性,则子视图将不会接收任何模型数据。 要将数据传输到分部视图,您可以在分部标签中使用

model
属性:

<partial name="/Views/Notes/Child.cshtml" model="Model" />

© www.soinside.com 2019 - 2024. All rights reserved.