-1

I'm experiencing the error NullReferenceException was unhandled by user code followed by Object reference not set to an instance of an object. I've read a number of questions including the very detailed answer here but can't understand why.

The line is occurring on the line vm.HomeView.ComputerName = Environment.MachineName;

When the error occurs, Environemnt.MachineName is correctly showing the machines name as expected so there is definitely a string variable trying to be assigned.

Could anyone help explain why.

Controller:

[HttpGet]
public ActionResult Index()
{
    InventoryLogViewModel vm = new InventoryLogViewModel();

    vm.HomeView.ComputerName = Environment.MachineName;
    vm.HomeView.RACFID = Environment.UserName;

    vm.AssetTypes = (from at in db.AssetTypes
                     orderby at.Name
                     select new AssetType
                     {
                         AssetTypeId = at.AssetTypeId,
                         Name = at.Name
                     }).ToList();

    return View(vm);

ViewModel:

namespace ControlsTeam.Models
{
    public class InventoryLogViewModel : _LayoutViewModel
    {
        public IEnumerable<Department> Departments { get; set; }
        public IEnumerable<AssetType> AssetTypes { get; set; }
        public Inventory Inventory { get; set; }
        public HomeView HomeView { get; set; }
    }

    public class HomeView
    {
        public string RACFID { get; set; }
        public string ComputerName { get; set; }
    }
}
Community
  • 1
  • 1
Gareth
  • 5,140
  • 5
  • 42
  • 73
  • You need to learn to debug your code. If `vm.HomeView` is null (you have not initialized it anywhere) then that exception will be thrown. Suggest you include a parameterless constructor in `InventoryLogViewModel` that initializes properties `HomeVew`, Inventory` `AssetTypes and `Departments` –  May 10 '15 at 00:49

1 Answers1

1

How, given this code:

InventoryLogViewModel vm = new InventoryLogViewModel();

could vm.HomeView (as used on the next line) be anything else then null ?

The InventoryLogViewModel constructor does not have an implementation, so its HomeView member after construction can only be null.

You may want to do the following:

InventoryLogViewModel vm = new InventoryLogViewModel() {
   HomeView = new HomeView() {
       RACFID = Environment.UserName,
       ComputerName = Environment.MachineName
   }
};
Alex
  • 13,024
  • 33
  • 62