将变量从ViewModel传递到ASP.NET MVC4中的View

时间:2012-12-11 20:30:39

标签: razor asp.net-mvc-4 viewmodel

我有这个ViewModel:

public DashboardViewModel(Dashboard dashboard)
        {
            HardwareType hwt = new HardwareType { HType = "PC" };
            IQueryable<Hardware> Pcs = db.Hardware.Where(h => h.HardwareType.Contains(hwt));

        }

我想将Pcs变量传递给我的视图,以便我可以遍历它。这是我的控制器:

 public ActionResult Index()
        {
            ViewBag.Title = "ULS Computer Inventory Tracker";

            Dashboard dashboard = new Dashboard();
            var dashbaordViewModel = new DashboardViewModel(dashboard);

            return View(dashboardViewModel);
        }

我的观点:

@{
    @model CIT.ViewModels.DashboardViewModel
}

...

 @foreach (var item in Pcs) {
    <li><a href="#" class="btn"><i class="icon-hdd"></i> @item.HardwareType</a></li>
 }

但是我收到一个错误,Pcs在当前上下文中不存在。我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

现在它存在Pcs作为一个仅存在于viewmodel构造函数中的变量,因此您需要将PCS变量作为成员级变量公开给ViewModel ..

    public IEnumerable<Hardware> Pcs { get; set; }

    public DashboardViewModel(Dashboard dashboard)
    {
        HardwareType hwt = new HardwareType { HType = "PC" };
        Pcs = db.Hardware.Where(h => h.HardwareType.Contains(hwt));
    }

答案 1 :(得分:0)

要使视图能够访问它,Pcs需要可以从实例范围公开访问。理想情况下,这应该通过公共财产来完成:

Public IEnumerable<Hardware> Pcs {get; private set;}

public DashboardViewModel(Dashboard dashboard)
{
    HardwareType hwt = new HardwareType { HType = "PC" };
    this.Pcs = db.Hardware.Where(h => h.HardwareType.Contains(hwt));
}

还应该通过视图中的模型引用它:

@foreach (Hardware item in Model.Pcs)