循环遍历ViewModel中的实体列表

时间:2015-01-18 21:31:46

标签: c# asp.net-mvc entity-framework razor

我的一个实体Create页面需要有一个其他实体的列表,在这种情况下,Timetable创建视图需要一个Station实体列表。为此,我创建了自己的ViewModel:

public class TimetablesCreateViewModel
{
    public Timetable Timetable { get; set; }
    public IEnumerable<Station> Stations { get; set; }
}

然后我将Create类中的TimetablesController方法更改为:

public ActionResult Create()
{
    TimetablesCreateViewModel model = new TimetablesCreateViewModel
    {
        Timetable = new Timetable(),
        Stations = db.Stations.ToList()
    };

    return View();
}

然后我修改了我的Create.cshtml页面以使用@model MyApp.ViewModels.TimetablesCreateViewModel,我正试图像这样循环Station

@foreach (var s in Model.Stations)
{
    <p>@s.Name</p>
}

当我加载/Timetables/Create页面时,我得到NullReferenceException

  

发生了'System.NullReferenceException'类型的异常   App_Web_lqnuresu.dll但未在用户代码中处理

     

附加信息:对象引用未设置为的实例   对象

我认为唯一可能造成这种情况的是,如果没有工作站填入Model.Stations,但事实并非如此,它已成功检索到数据库中的所有工作站。

1 个答案:

答案 0 :(得分:1)

您需要使用视图返回模型:

return View(model);

相关问题