经过查询结果在viewbag [英] Passing query results in a viewbag

查看:343
本文介绍了经过查询结果在viewbag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来应该是很容易的,但我已经试过三个或四个办法做到这一点(但无济于事)。

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

我只是试图把查询结果在viewbag并显示它。

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

我试过投入ViewBag模型对象列表:

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;

然后我试着吐出一个.cshtml:

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 />
}

但它说:

无法将类型
  System.Data.Entity.Infrastructure.DbQuery
  至
  System.Collections.Generic.List

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

所以看起来我使用了错误的模板使用。我如何吐出一个System.Entity.Infrastructure.DbQuery?

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

我也尝试通过Viewbag传递结果字符串列表。 (那是一个糟糕的方​​式做到这一点?)

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 )   
}

和我得到这样的:

对象引用不设置到
  实例的对象。

Object reference not set to an instance of an object.

和它在的foreach关键字百分点。

And it points at the "foreach" keyword.

这是否意味着有没有消息?还是什么?

Does that mean there were no messages? Or what?

我希望有展示如何把queryresults在ViewBag以及如何让他们走出的教程!我见过不尊重返回object.ToList()任何形式的,其中机制的教程,但没有例子拉出了几下,相关条目并显示出来。

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.

推荐答案

尝试

ViewBag.messages = MSG.ToList();

此外,System.Data.Entity.Infrastructure.DbQuery实现IEnumerable(<一个href=\"http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbquery(v=vs.103).aspx\">http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbquery(v=vs.103).aspx ),所以这也应该工作:

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;

这篇关于经过查询结果在viewbag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆