从控制器发送到视图时模型为空

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

我认为

System.NullReferenceException
会得到
Model

@page
@model List<MyApp.Models.Student>

<div>
  @{
    string sHtml = TestPageView.GetHtml(Model); // <-- NullReferenceException here
  }

  @Html.Raw(sHtml)
</div>

这是我的控制器操作:

public IActionResult TestPage()
{
  return View(SomeStudents.Students);
}

这是我的

Student
模型:

namespace Models
{
  public class Student
  {
    public int Id;
    public string Name;
    public int Age;
    public int Grade;
  }
}

...列表来自这里:

namespace Data {
  public class SomeStudents {
    public static List<Student> Students { get; } = new List<Student>() {
      new Student() { Id = 1, Name = "Adam", Age = 20, Grade = 69 },
      new Student() { Id = 2, Name = "Mark", Age = 21, Grade = 80 },
      new Student() { Id = 3, Name = "Bill", Age = 18, Grade = 51 }
    };
  }
}

我回顾了几个报告相同问题的稍微相似的问答,包括:

...但我没有找到任何可以解决我的确切场景的内容(我认为这非常简单,一点也不复杂,这是令人困惑的)。

我尝试显式命名视图,如这个答案

public IActionResult TestPage()
{
  return View("TestPage", SomeStudents.Students);
}

我还尝试稍微调整视图,使用此示例中稍微修改的摘录:

@page
@model List<MyApp.Models.Student>

<div>
  @foreach (var item in Model) { // <-- NullReferenceException here
    @Html.DisplayFor(modelItem => item.Name)
  }
</div>

但是,在所有情况下,尝试在视图中访问

Model
都会导致相同的
NullReferenceException

如何将

Student
列表传递到我的视图?

asp.net-mvc asp.net-core view model controller
1个回答
0
投票

解决方案是删除

@page
指令。

该指令适用于 Razor 页面,而不是 MVC 视图。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.