razor 中的嵌套 for 循环
我有一个带有 Razor 的 ASP.Net MVC 应用程序。我尝试访问视图中的集合。这是我的代码:
@foreach (var question in ViewBag.Questions) {
<p>@question.Name</p>
foreach (var answer in question.Answers) {
<input type="radio" name="@answer.QuestionId" value='@answer.id' /> @answer.Text<br />
}
}
在 foreach (var answer in question.Answers)
我得到:
“ObjectContext 实例已被释放,不能再用于需要连接的操作。”
对于 Questions
集合,我有一个 .ToList()
,但是如果我想访问 ti,我该如何处理 Answers
集合?在运行时?
I have a ASP.Net MVC app with Razor. I try to access a collection in the view. Here is my code:
@foreach (var question in ViewBag.Questions) {
<p>@question.Name</p>
foreach (var answer in question.Answers) {
<input type="radio" name="@answer.QuestionId" value='@answer.id' /> @answer.Text<br />
}
}
At foreach (var answer in question.Answers)
I get:
"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."
I have a .ToList()
when it comes to the Questions
collection but what do I do with the Answers
collection if I want to access ti at runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确保您已在控制器中急切地加载了
Answers
集合:关于
ViewBag
,您可以使用视图模型来代替。更不用说您的问题纯粹与您正在使用的数据访问技术(我想是 EntityFramework)有关,与 ASP.NET MVC 无关。Make sure you have eagerly loaded the
Answers
collection in your controller:And concerning
ViewBag
, well, you could have used a view model instead. Not to mention that your problem is purely related to the data access technology you are using (I suppose EntityFramework) and has nothing to do with ASP.NET MVC.您需要将问题投影到一个新对象中,并将答案集合
ToArray
投影到一个新对象中。您还可以使用
.Load
或.Include
预先加载 Answers 集合You would need to project the question into a new object and
ToArray
the answers collection.You can also eager load the Answers collection by using
.Load
or.Include