将字符串分配给ViewModel

时间:2015-05-10 00:41:53

标签: c# asp.net-mvc nullreferenceexception

我遇到错误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);

视图模型:

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

1 个答案:

答案 0 :(得分:1)

如果给出这段代码:

InventoryLogViewModel vm = new InventoryLogViewModel();

可以vm.HomeView(在下一行中使用)是null之后的其他内容吗?

InventoryLogViewModel构造函数没有实现,因此构造后的HomeView成员只能是null

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

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