Using a viewbag to pass query results

asp.net-mvc-3 ef-code-first entity-framework

Question

Although it looks so simple, I've tried three or four different approaches (but to no avail).

I'm only attempting to show a query result in a viewbag.

I've attempted to include a list of model objects in a ViewBag:

var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG;
ViewBag.messages = MSG;

I then attempt to output it as a.cshtml:

var message = (List<LemonTrader.Models.Message>)ViewBag.messages;  // <--- fails here because it is a string
foreach ( var MSG in message )
{
@Html.Label(MSG.msg)<br />
}

Yet it claims:

Cannot convert type 'System.Data.Entity.Infrastructure.DbQuery' to 'System.Collections.Generic.List'

So it seems that I'm using the incorrect template. A System.Entity.Infrastructure.DbQuery cannot be thrown out in any way.

As a list of strings, I've also tried sending the results via the Viewbag. (Is doing it that way a bad way?)

var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG.msg;
ViewBag.messages = mesg;

Moreover, it was vomited out as a string list:

foreach (var atext in ViewBag.messages as List<string>) { // gets hung up on foreach here (why???)
    @Html.Label( atext )   
}

Then I understand:

Object reference not set to an instance of an object.

And it makes a reference to the phrase "foreach."

Does it imply that no messages were sent? What else?

I wish there was a tutorial that showed how to insert and remove query results from a ViewBag! Tutorials that return an object have been observed. Without regard to any kind of "where" method, ToList() is used without any examples to choose a small number of pertinent elements and show them.

1
5
5/21/2011 9:08:47 AM

Accepted Answer

Try

ViewBag.messages = MSG.ToList();

System.Data.Entity.Infrastructure is another. This should also work since DbQuery implements IEnumerable (http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbquery(v=vs.103).aspx):

var message = (IEnumerable<LemonTrader.Models.Message>)ViewBag.messages;
6
5/21/2011 9:17:00 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow