ICollection in Viewmodel causing a Null Reference exception

-1

I am having trouble with this. I am trying to add a viewmodel oject to an ICollection of viewmodel objects...

It gives a Null Reference Exception. Here is the inner exception.

  System.NullReferenceException occurred
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=<Cannot evaluate the exception source>

Its saying it cannot evaluate the exception source....

I have a viewmodel:

    public class ClientJobListingViewModel
{
    public int Id { get; set; }
    public string JobType { get; set; }
    public string Status { get; set; }
    public string WarrantyStatus { get; set; }
    public string NumberOfVisits { get; set; }
}

that is added to an entity as a collection of viewmodels:

public class ClientDetailsViewModel
{
    ...
    public ICollection<ClientJobListingViewModel> Jobs { get; set; }
}

I am using a foreach loop to create the viewmodel and then add it to the collection... simple.

if (_client.Jobs.Count() > 0)
{
     foreach (Job job in _client.Jobs)
     {
          var _job = new ClientJobListingViewModel();

          _job.JobType = "test1";
          _job.Status = "test2";
          _job.WarrantyStatus = "test3";
          _job.NumberOfVisits = "4";

          _model.Jobs.Add(_job);
          }
     }
....

Yet when I run this I am getting a null reference exception error..

Showing that the view model is not null.

It looks like I have coded this correctly but maybe I have missed something.. Visual Studio certainly thinks so..

What am I doing wrong?

c#
asp.net-mvc
asked on Stack Overflow Feb 23, 2017 by si2030 • edited Feb 23, 2017 by si2030

1 Answer

3

You have to initialize Jobs property in ClientDetailsViewModelconstructor or before use of _model.Jobs.Add(_job);

 public class ClientDetailsViewModel
{
    public ClientDetailsViewModel()
    {
        Jobs = new List<ClientJobListingViewModel>();
    }
    public ICollection<ClientJobListingViewModel> Jobs { get; set; }
}
answered on Stack Overflow Feb 23, 2017 by Jignesh Variya

User contributions licensed under CC BY-SA 3.0