Using a viewbag to pass query results

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

Question

This seems like it should be so easy, but I've tried three or four ways to do it (but to no avail).

I'm just trying to put a query result in a viewbag and display it.

I've tried putting a model object list in a ViewBag:

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

And then I try to spit it out in 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 />
}

But it says:

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

So it seems I'm using using the wrong template. How do I spit out a System.Entity.Infrastructure.DbQuery?

I've also tried passing the results through the Viewbag as a list of strings. (Is that a worse way to do it?)

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

And spitting it out as a string list:

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

And I get this:

Object reference not set to an instance of an object.

And it points at the "foreach" keyword.

Does that mean there were no messages? Or what?

I wish there was a tutorial showing how to put queryresults in a ViewBag and how to get them out! I've seen tutorials that return an object.ToList() without respect to any kind of "where" mechanism, but no examples to pull out a few, relevant entries and display them.

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

Accepted Answer

Try

ViewBag.messages = MSG.ToList();

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

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