1

One of my entities Create page needs to have a list of other entities, in this case the Timetable create view needs a list of Station entities. To achieve this I created my own ViewModel:

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

I then changed my Create methods in the TimetablesController class to be this:

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

    return View();
}

I then modified my Create.cshtml page to use @model MyApp.ViewModels.TimetablesCreateViewModel, and I'm attempting to loop through Stations like this:

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

When I load the /Timetables/Create page, I get a NullReferenceException:

An exception of type 'System.NullReferenceException' occurred in App_Web_lqnuresu.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

The only thing I thought would be causing this is if no stations were populated into Model.Stations, but that's not the case, it's successfully retrieving all the stations in the database.

John Dorean
  • 3,744
  • 9
  • 51
  • 82

1 Answers1

1

You need to return the model with the view:

return View(model);

macoms01
  • 1,110
  • 13
  • 22