繁体   English   中英

在 ASP.NET 核心 Razor 页面中填充下拉列表时获取 null 引用异常

[英]Getting null reference exception when populating dropdown list in ASP.NET Core Razor Pages

我是 ASP.Net 核心的新手。 我正在尝试从Instructor model 填充 class Createmodel中的下拉列表并获得“空引用”异常。

这是 cshtml.cs 文件中的代码:

public SelectList Instructors { get; set; }

public async Task OnGetAsync()
{
    var students = from s in _context.User_Profile
                   select s;

    if (!string.IsNullOrEmpty(SearchString))
    {
        students = students.Where(s => s.FirstName.Contains(SearchString));
    }

    UserProfile = await students.ToListAsync();

    var instructors = from i in _context.Instructor
                      orderby i.FirstName
                      select i;
       
    Instructors = new SelectList(instructors, "ID", "FirstName");
}

我的 cshtml 视图中有以下标记:

<div class="form-group">
    <label asp-for="Class_Info.Instructor" class="control-label"></label>
    <select asp-for="Class_Info.Instructor" class="form-control" asp-items="@Model.Instructors">
         <option value="">-- Select --</option>
    </select>
</div>

我在以下位置收到错误:

@Model.Instructors

我得到了这个例外这个错误

请指教...

我在这里拼错了字段名称:

Instructors = new SelectList(instructors, "ID", "FirstName");

将其更改为:

Instructors = new SelectList(instructors, "InstructorID", "FirstName");

它开始工作了。 谢谢你们每一个人的帮助!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM