【问题标题】:Looping through list of entities in a ViewModel [duplicate]遍历 ViewModel 中的实体列表 [重复]
【发布时间】:2015-01-18 21:31:46
【问题描述】:

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

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

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

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

    return View();
}

然后我修改了我的Create.cshtml 页面以使用@model MyApp.ViewModels.TimetablesCreateViewModel,并且我正尝试像这样循环遍历Stations:

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

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

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

附加信息:对象引用未设置为 对象。

我认为唯一会导致这种情况的是,如果没有电台被填充到 Model.Stations,但事实并非如此,它成功地检索了数据库中的所有电台。

【问题讨论】:

  • 您没有将模型传递给您的视图。使用return View(model);
  • return View(model);

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


【解决方案1】:

您需要返回带有视图的模型:

return View(model);

【讨论】:

    猜你喜欢
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2017-12-25
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多