Creating and Displaying many to many relationships part 3

Continuation of Creating and Displaying N to N Relationships part 2

First let’s look at what we want to display in our View

This is what a typical grade sheet displaying the many:many relationship between students and grades would look like –  so how do we do this?

First I am going to Create a new View – simply right click, Add View – and set the options

Now I am going to first do this the simplest method – use of the ViewBag, I first need a controller – and I will add the Controller method to the GradesController – which of course must be named to match the View “ViewAsTable”. I am also going to add to the ViewBag all the elements I need to create the display

Add the following method to your GradesController

 public ActionResult ViewAsTable()

        {

            ViewBag.ClassId = new List<Class>(db.Classes);

            ViewBag.StudentId = new List<Student>(db.Students);

            ViewBag.GradeId = new List<Grade>(db.Grades);

            return View();

        } 

Next I will create the code to display in the View. Note the use of the foreach loops – one for the header (to display classes) and the 2 embedded loops to display students and grades.

ViewAsTable.cshtml

@model SampleNtoN.Models.Grade
@{
    ViewBag.Title = "View As Table";
}
<h2>View As Table</h2>
<table class="table">
    <tr>
        <th></th>
        @foreach (var c in ViewBag.ClassId)
        {
            <th>@c.ClassName</th>
       }
    </tr>
    @foreach (var s in ViewBag.StudentId)
    {
        <tr>
            <td>
                @s.StudentName
            </td>
            @foreach (var c in ViewBag.ClassId)
            {
           <td>
                @foreach (var g in ViewBag.Gradeid)
                {
                    if((g.StudentId == s.StudentId)&&(g.ClassId==c.ClassId))
                    {
                        @g.Grade1
                    }
                }
            </td>
            }
        </tr>
    }
</table>

Some good references – there are quite a few ways to do this and I am only demonstrating what I see as the simplest of the solutions.

https://www.codeproject.com/Articles/1110431/Gridview-in-ASP-NET-MVC

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application