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..
It looks like I have coded this correctly but maybe I have missed something.. Visual Studio certainly thinks so..
What am I doing wrong?
You have to initialize Jobs
property in ClientDetailsViewModel
constructor or before use of _model.Jobs.Add(_job);
public class ClientDetailsViewModel
{
public ClientDetailsViewModel()
{
Jobs = new List<ClientJobListingViewModel>();
}
public ICollection<ClientJobListingViewModel> Jobs { get; set; }
}
User contributions licensed under CC BY-SA 3.0