【问题标题】:Controller doesn't update Razor view model: how to pass value to a view控制器不更新 Razor 视图模型:如何将值传递给视图
【发布时间】:2020-07-23 07:29:12
【问题描述】:

我正在尝试使用 Razor 和 .net Core 构建一个简单的网页。

我的控制器:

[HttpGet("/api/employees")]

public ActionResult Index()
{
    MyPaginationModel aux = new MyPaginationModel();
    aux.Employees = new List<EmployeeViewModel> {
    new EmployeeViewModel{
        Name = "Test",
        Surname = "Test",
        }
    };
    return View(aux);
}

我的看法:

@page


@model MyPaginationModel

<table class="table table-striped">
    @foreach (var item in Model.Employees)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Surname</td>
        </tr>
    }
</table>

MyPaginationModel:

public class MyPaginationModel : PageModel
{
    public List<EmployeeViewModel> Employees { get; set; }
}

还有 EmployeeViewModel:

public class EmployeeViewModel
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

它抱怨 Model.Employees 的 nullreferencepointexception。所以,不知何故,我需要将我在控制器中创建的实例传递给视图。

【问题讨论】:

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


    【解决方案1】:

    因为@page 指令将视图变成了 MVC 动作。 这意味着它直接处理请求,而不通过控制器。

    更多信息:Razor Pages in ASP.NET Core

    解决方法:

    1. 删除:@page

    2. 地址:@using MyPaginationModel Namespace

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多