Razor Pages PageModel 正在返回 Null 属性

问题描述

为什么这个 razor 页面为 Model.People 返回 null 属性

People.cshtml.cs

public class PeopleModel : PageModel
{
    [BindProperty]
    public List<PeopleObj> People { get; set; }

    public void OnGet()
    {
        List<PeopleObj> People = GetPeople().ToList();//returns 4 people
    }
}

People.cshtml

@page
@model MyProject.Pages.PeopleModel

@foreach (var item in Model.People){
//Model.People is null 
}

会发生什么是 OnGet 被调用并填充人员列表,但是当视图被点击时,视图抛出 System.NullReferenceException: 'Object reference not set to an instance of an object。'在 Model.People 上。视图的人为空。我不明白为什么在 OnGet 中设置后它会被空值覆盖。

编辑 似乎问题在于声明类型。我仍然想知道为什么这会破坏模型。

List<PeopleObj> People =

解决方法

因为你使用了List<PeopleObj> People = GetPeople().ToList();//returns 4 people,你只是创建了一个新列表,你没有初始化[BindProperty]public List<PeopleObj> People { get; set; }。 所以当你使用foreach时,list(Model.People)为null。null不能为foreach。

人员: enter image description here

解决方案:

如果要设置 PeopleModel 的属性,可以更改

List<PeopleObj> People = GetPeople().ToList();

People = GetPeople().ToList();

然后您仍然可以从 OnPost 处理程序中的 People 获取编辑后的数据。

这是一个演示:

型号:

public class PeopleObj 
        {
            public int Id { get; set; }
            public string Name { get; set; }
    
        }

People.cshtml:

<form method="post">
    @{var count = 0;}
    @foreach (var item in Model.People)
    {
        <div class="form-group">
            <label class="control-label">Id</label>
            <input class="form-control" value="@item.Id" name="People[@count].Id"/>
        </div>
        <div class="form-group">
            <label class="control-label">Name</label>
            <input class="form-control" value="@item.Name" name="People[@count].Name" />

        </div>
        count++;
    }
    <input type="submit" value="submit" />
</form>

People.cshtml.cs:

public class PeopleModel : PageModel
    {
        [BindProperty]
        public List<PeopleObj> People { get; set; }

        public void OnGet()
        {
            People = new List<PeopleObj> { 
                new PeopleObj{  Id=1,Name="person1"},new PeopleObj{  Id=2,Name="person2"},new PeopleObj{  Id=3,Name="person3"},new PeopleObj{  Id=4,Name="person4"}
            };
        }
        public void OnPost()
        {
            //get edited data from People
            List<PeopleObj> EditedPeople = People;
        }
    }

结果: enter image description here