在viewbag中传递查询结果 [英] Passing query results in a viewbag

查看:107
本文介绍了在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?

我希望有一个教程显示如何将查询结果放在ViewBag中,以及如何让它们出来!我已经看到教程返回一个object.ToList()而不考虑任何一种where机制,但没有任何示例可以拉出一些相关的条目并显示它们。

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( http://msdn.microsoft.com/en -us / library / system.data.entity.infrastructure.dbquery(v = vs103).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天全站免登陆