[英]Getting null reference exception when populating dropdown list in ASP.NET Core Razor Pages
I am new to ASP.Net core.我是 ASP.Net 核心的新手。 I am trying to populate dropdown list in class Createmodel
from the Instructor
model and getting a "Null reference" exception.我正在尝试从Instructor
model 填充 class Createmodel
中的下拉列表并获得“空引用”异常。
This is the code in cshtml.cs file:这是 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");
}
I have the following markup in my cshtml view:我的 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>
I am getting the error at:我在以下位置收到错误:
@Model.Instructors
I am getting this exception我得到了这个例外
Please advise...请指教...
I had misspelled the field name here:我在这里拼错了字段名称:
Instructors = new SelectList(instructors, "ID", "FirstName");
Changed it to:将其更改为:
Instructors = new SelectList(instructors, "InstructorID", "FirstName");
And it started working.它开始工作了。 Thank you everyone for your help!!谢谢你们每一个人的帮助!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.