-2

I am trying to take Courses and Assignments from a stored procedure. Populate my ViewModel with the results, and display them on the view with all the assignments per course under its course. The stored procedures return lists of the items. I am getting a Null reference exception.

My Controller code:

var CourseNames = storedProcedure.getCourseNames(User.Identity.Name);

    var CoursesView = new CoursesViewModel();

    foreach (var CourseName in CourseNames)
    {
        CoursesView.CourseNames.Add(CourseName);
        var AssignmentNames = storedProcedure.getAssignmentNames(User.Identity.Name, CourseName);
        foreach (var AssignmentName in AssignmentNames)
        {
            CoursesView.AssignmentNames.Add(AssignmentName);
        }
    }

    return View(CoursesView);

The CoursesView.CourseNames.Add(CourseName); line errors out

My ViewModel Code:

public class CoursesViewModel
    {
        public List<string> CourseNames { get; set; }       
        public List<string> AssignmentNames { get; set; }
    }

My View Code:

<table>
    @foreach (var item in Model)
        {
            <tr><th>@Model.CourseNames</th></tr>
            <tr><td>@Model.AssignmentNames</td></tr>
        }
</table>
Kéiro
  • 13
  • 5

1 Answers1

0

Assuming you haven't slimmed down the code for brevity, I believe the issue is that your CoursesViewModel class isn't initializing the List properties, and thus when you call Add on either of them, you'll get the NullReferenceException.

Here is how I would fix it (though you could move the initialization into the controller, if you so chose):

public class CoursesViewModel
{
    public List<string> CourseNames { get; set; }       
    public List<string> AssignmentNames { get; set; }

    public CoursesViewModel()
    {
        CourseNames = new List<string>();
        AssignmentNames = new List<string>();
    }
}
Chris Thompson
  • 490
  • 5
  • 17
  • Thank you, this solved the NullReferenceException but now im getting System.InvalidOperationException. – Kéiro Nov 09 '17 at 05:01