3

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?

2 Answers 2

3

Make sure you have eagerly loaded the Answers collection in your controller:

public ActionResult Foo()
{
    ViewBag.Questions = db.Questions.Include("Answers").ToList();
    return View();
}

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You would need to project the question into a new object and ToArray the answers collection.

You can also eager load the Answers collection by using .Load or .Include

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.