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
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!!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With