Hey everyone! I’m working on tweaking the Contoso University app and I need some help. I want to show a list of courses each student is enrolled in, separated by commas. I’ve got the basic setup with students, courses, and enrollments, but I’m not sure how to put it all together.
Here’s what I’ve got so far:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
public class Enrollment
{
public int StudentId { get; set; }
public int CourseId { get; set; }
}
I’m thinking I need to do something in the view, maybe using LINQ? But I’m not sure how to start. Any tips or code snippets would be super helpful! Thanks in advance!
I’ve tackled a similar issue before, and here’s an approach that worked well for me:
You can leverage LINQ directly in your view to generate the comma-separated list. This keeps your controller lean and pushes the logic to where it’s being used.
In your Razor view, try something like this:
@foreach (var student in Model)
{
<div>
<h3>@student.Name</h3>
<p>Courses: @string.Join(", ", student.Enrollments.Select(e => e.Course.Title))</p>
</div>
}
This assumes you’re passing a list of Students to your view. The string.Join method combined with LINQ’s Select creates the comma-separated list of course titles.
If you need this data in multiple places, consider creating an extension method on the Student class to encapsulate this logic. It would improve reusability and keep your code DRY.
Hey SwimmingDolphin! That’s a cool project you’re working on. 
I think I might have an idea that could help you out. Have you considered using a view model for this? It could make things a bit easier to manage.
Maybe something like this:
public class StudentViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string EnrolledCourses { get; set; }
}
Then in your controller, you could do something like:
var viewModel = _context.Students
.Select(s => new StudentViewModel
{
Id = s.Id,
Name = s.Name,
EnrolledCourses = string.Join(", ", s.Enrollments.Select(e => e.Course.Title))
})
.ToList();
This way, you’re doing the heavy lifting in the controller, and your view stays nice and clean. What do you think? Would this work for what you’re trying to do?
Oh, and I’m curious - what made you choose the Contoso University app to work on? Are you learning ASP.NET Core?
hey swimingdolphin, have u tried using a computed property in ur Student class? it could look smth like this:
public string EnrolledCourses => string.Join(", ", Enrollments.Select(e => e.Course.Title));
then u can just use Student.EnrolledCourses in ur view. makes it super easy!