将字符串分配给 ViewModel 时出现 NullReferenceException

NullReferenceException when Assigning String to ViewModel

我遇到错误 NullReferenceException was unhandled by user code 后跟 Object reference not set to an instance of an object. 我已经阅读了很多问题,包括非常详细的答案 here 但不明白为什么。

行发生在行vm.HomeView.ComputerName = Environment.MachineName;

发生错误时,Environemnt.MachineName 正确显示了预期的机器名称,因此肯定有一个字符串变量正在尝试分配。

谁能帮忙解释一下原因。

控制器:

[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; }
    }
}

如何,给定这段代码:

InventoryLogViewModel vm = new InventoryLogViewModel();

vm.HomeView(在下一行中使用)可以是 null 以外的任何东西吗?

InventoryLogViewModel构造函数没有实现,所以构造后其HomeView成员只能是null.

您可能需要执行以下操作:

InventoryLogViewModel vm = new InventoryLogViewModel() {
   HomeView = new HomeView() {
       RACFID = Environment.UserName,
       ComputerName = Environment.MachineName
   }
};