简体   繁体   English

从数据库中创建一个选择框列表并将其显示在 asp.net mvc 的视图中

[英]making a selectboxlist from database and show it in a view in asp.net mvc

I used this code for making data for selectbox and used viewbag to send it to view:我使用此代码为选择框制作数据并使用 viewbag 将其发送到视图:

 ViewBag.category_id = new SelectList(db.categories, "id", "title");
                return View();

在此处输入图像描述

and in my view to show the selectbox I used this code:在我看来,为了显示选择框,我使用了以下代码:

@Html.DropDownList("category_id", null, htmlAttributes: new { @class = "form-control" })

but when I run my project I get this error: System.InvalidOperationException: 'The operation cannot be completed because the DbContext has been disposed.'但是当我运行我的项目时,我收到此错误: System.InvalidOperationException: '该操作无法完成,因为 DbContext 已被处置。

在此处输入图像描述

db.Categories is a lazy-loaded IEnumerable<> of all of the categories in your database. db.Categories 是数据库中所有类别的延迟加载 IEnumerable<>。 You should use ToList() to evaluate that IEnumerable<> just like you did with your other queries:您应该使用 ToList() 来评估 IEnumerable<> 就像您对其他查询所做的那样:

ViewBag.category_id = new SelectList(db.categories.ToList(), "id", "title");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM