score:2

Accepted answer

Your top level foreach would be something like

foreach (var courseGroup in Model.GroupBy(m => m.CourseName))

And each item would be:

<h2>courseGroup.Key</h2>

<table class="table">
    @foreach (var item in courseGroup)
    {
        <tr>
            <td>@item.DishName</td>
            <td class="text-right">@item.Price</td>
        </tr>
    }
</table>

However, you can organise your data a bit more, so if you defined your classes (and tables in your database), as something like this:

public class Course
{
    public string CourseName { get; set; }
    public List<Dish> Dishes { get; set; }
}

public class Dish
{
    public string DishName { get; set; }
    public decimal Price { get; set; }
}

Then your code becomes a lot simpler:

foreach (var course in Model) //or Model.Courses - up to you

And each item would be:

<h2>course.CourseName</h2>

<table class="table">
    @foreach (var item in course.Dishes)
    {
        <tr>
            <td>@item.DishName</td>
            <td class="text-right">@item.Price</td>
        </tr>
    }
</table>

score:0

Thanks Rob for your help. I appreciate it! I choose for the first option. I had to extend the Controller code with a lamda-expression .Include(m => m.Course) because I needed to include the property (CourseName) of the first class (Course.cs). The Dish class had already Lookup property public Course Course { get; set; }) So I changed the top level foreach in @foreach (var courseGroup in Model.GroupBy(m => m.Course.CourseName)) and then everything worked out fine.

The second option did not work. I think because of the demodata that is related between the two classes Course.cs an Dish.cs that has a CourseId property.

Cheers!


Related Query