I have a ASP.Net MVC app with Razor. I try to access a collection in the view. Here is my code:
@foreach (var question in ViewBag.Questions) {
<p>@question.Name</p>
foreach (var answer in question.Answers) {
<input type="radio" name="@answer.QuestionId" value='@answer.id' /> @answer.Text<br />
}
}
At foreach (var answer in question.Answers) I get:
“The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.”
I have a .ToList() when it comes to the Questions collection but what do I do with the Answers collection if I want to access ti at runtime?
Make sure you have eagerly loaded the
Answerscollection in your controller:And concerning
ViewBag, well, you could have used a view model instead. Not to mention that your problem is purely related to the data access technology you are using (I suppose EntityFramework) and has nothing to do with ASP.NET MVC.