views:

203

answers:

2

Hi, I'm facing the following problem: in the controller I select the data I need and store it into the ViewData;

using (Models.SkedruleEntities ctx = new Models.SkedruleEntities())
{
    ViewData["users"] = (from u in ctx.User select u);
}

In the View I try to read from the ViewData like this:

<p>
    <%foreach(User user in (IEnumerable<User>)ViewData["users"]) { %>
        <div><%=user.Name %></div>
    <%}%>
</p>

But I get a System.ObjectDisposedException error, as the ViewData seems to contain the query, not the data retrieved by the query and of course the context ctx is no more available.

Any help? Thanks

+2  A: 

Just add ToList():

ViewData["users"] = (from u in ctx.User select u).ToList();
eu-ge-ne
+2  A: 

You're storing the query in the view data, not the results. So in the view you get the query back and execute it. At that moment the context is already disposed.

The solution is to execute the query in the controller and store the result in the ViewData:

ViewData["users"] = (from u in ctx.User select u).ToList();
Thomas Freudenberg