First I've read through the answers given here which are very useful: How to write a simple Html.DropDownListFor()?
They helped for when you just have one model and nothing to iterate over except for the instances created from that model, but what do you do when you have an enumerable inside of a model, that you want to create a drop down for?
What I'm trying to do is create a dropdown list from a list of students and display their First Name and Last Name as the fields, with their own object or ID as the value fields.
StudentsCourses Viewmodel
public class StudentsCourses
{
public ICollection<Student> Students;
public ICollection<Course> Courses;
}
Students model
public class Student
{
public int ID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Enrollment Date")]
[DataType(DataType.Date)]
public DateTime EnrollmentDate { get; set; }
public ICollection<Enrollment> Enrollments { get; set;}
}
I'm feeding the viewmodel into the view via this in the controller:
public IActionResult Index()
{
StudentsCourses sc = new StudentsCourses()
{
Courses = _context.Courses.ToList(),
Students = _context.Students.Include(e => e.Enrollments).ThenInclude(c => c.Course).ToList()
};
return View(sc);
}
This is what I have so far on the view:
<h3>Register a Course</h3>
<form asp-action="Index">
<div class="form-group">
<label class="control-label">Select Student</label>
@Html.DropDownListFor(n => n.Student, new SelectList(Model.Students, "FirstMidName", "LastName"))
</div>
</form>
But it does not work, there is a red squiggly under "n.student" from "n => n.Student)"