0
votes

I'm try to return a list from my view model that contains a list of employee full names. However the values are returning as null and I can't seem to figure out why. I'm also greeted with this lovely error:

Object reference not set to an instance of an object.

The error specifically shows my foreach loop in my AllEmployees() method as being the issue

Here is my entity:

namespace ROIT.Entities
{
public class Employee : Entity<Employee>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [NotMapped]
    public string FullName {
        get { return FirstName + " " + LastName; }
    }
}
}

Here is my view model:

namespace ROIT.Web.Models
{
   public class ContractPageViewModel
{
   public ICollection<Contract> Contracts { get; set; }
   public Contract Contract { get; set; }
   public ICollection<Roi> Rois { get; set; }
   public ICollection<Employee> Employees { get; set; }
   public ICollection<ContractResource> ContractResources { get; set; }
   public ICollection<LaborCategory> LaborCategories{ get; set; }
   public List<string> AllEmployeesList { get; set; }

   public void AllEmployees()
   {
       AllEmployeesList = new List<string>();
       foreach (Employee item in Employees)
       {
           AllEmployeesList.Add(item.FirstName);
       }
   }

}
}   

And heres the return in my controller:

public ActionResult testview()
    {
        var model = new ContractPageViewModel();
        model.Contracts = db.Contracts.Include(c => c.Business).Include(c => c.Customer).ToList();
        model.AllEmployees();

        return View(model);
    }

Let me know if you need any more clarification.

Thanks in advance

2
Your getting that error because ContractPageViewModel.Employees's value is never set.Jay
@Ger Hey friend, welcome to StackOverflow! Please, visit the /about page to learn how the network works. Don't forget to upvote the answers that deserve it and to mark as correct the answer that solved your problem. You're encouraged to do the same on your other questions.Andre Calil

2 Answers

1
votes

Your Employees variable:

public ICollection<Employee> Employees { get; set; }

...is not being instantiated before you try to loop through it. More clearly, declaring it as a property does not set the instance of Employees equal to anything; so unless you are setting it elsewhere (not shown above) it will be null when you try to access it.

0
votes

You must assign a list to Employees just like you do to Contract. When you call AllEmployees method, that object is still null.

Side note: you could rewrite your property to something like:

public ICollection<Employee> Employees { get; set; }
public List<string> AllEmployeesList 
{ 
    get
    {
        return this.Employees.Select<Employee, string>(x => x.FirstName).ToList();
    }
    private set; 
}