Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am new to ASP.Net core. I am trying to populate dropdown list in class Createmodel from the Instructor model and getting a "Null reference" exception.

This is the code in cshtml.cs file:

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:

<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 This Error

Please advise...

like image 697
Reet Avatar asked Aug 31 '25 16:08

Reet


2 Answers

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!!

like image 121
Reet Avatar answered Sep 02 '25 14:09

Reet


For those who might encounter this error but had all the spelling checked out. Another instance is that you're passing a field instead of a property for dataValueField and dataTextField when initializing the SelectList. Make sure to have those getter/setter. Thats all! Happy Debugging! :P

like image 25
Noobie Avatar answered Sep 02 '25 12:09

Noobie