razor 中的嵌套 for 循环

发布于 2025-01-07 20:49:53 字数 589 浏览 0 评论 0原文

我有一个带有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我不在是我 2025-01-14 20:49:53

确保您已在控制器中急切地加载了 Answers 集合:

public ActionResult Foo()
{
    ViewBag.Questions = db.Questions.Include("Answers").ToList();
    return View();
}

关于 ViewBag,您可以使用视图模型来代替。更不用说您的问题纯粹与您正在使用的数据访问技术(我想是 EntityFramework)有关,与 ASP.NET MVC 无关。

Make sure you have eagerly loaded the Answers collection in your controller:

public ActionResult Foo()
{
    ViewBag.Questions = db.Questions.Include("Answers").ToList();
    return View();
}

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.

东走西顾 2025-01-14 20:49:53

您需要将问题投影到一个新对象中,并将答案集合 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文