我以为我开始了解如何在 MVC 中使用 DDL,但我想我仍然没有真正获得正确的设置。
我有一个 DropDownList,我从 Entity Framework 填充并使用存储库。我可以通过代码进行调试,并看到 ViewModel 正在填充值,但是一旦我到达 View ,我就会得到错误 "The operation cannot be completed because the DbContext has been disposed"
。我想当我到达 View 时,DbContext 已经不再需要了?
我尝试了 Html.DropDownList 和 Html.DropDownListFor 的不同组合,每次我都会得到相同的消息。我确信这是一些简单的事情,我只是不理解,但我一直在研究不同的示例并尝试几种不同的组合,但没有任何运气。
这是我的 View 模型
public class AssignCounselorViewModel
{
public IEnumerable<SelectListItem> listMerits { get; set; }
public int MeritSelectedId { get; set; }
}
这是我的 Controller :
public ActionResult AssignCounselor()
{
var viewModel = new AssignCounselorViewModel();
viewModel.listMerits = MeritCounselorRepository.GetAllMerits();
return View(viewModel);
}
这是我的存储库:
public static IEnumerable<SelectListItem> GetAllMerits()
{
using (DataContext ctx = new DataContext())
{
var results = (from m in ctx.MeritBadges
select new SelectListItem
{
Value = m.ID.ToString(),
Text = m.MeritBadgeName
}
).OrderBy(o => o.Text);
return new SelectList(results, "Value", "Text");
}
}
这是我的观点:
<div class="row">
<div class="col-md-12">
@Html.DropDownListFor(m => m.listMerits,
new SelectList(Model.listMerits, "Text", "Value"))
</div>
</div>
以下是我尝试过的其他一些组合。
@Html.DropDownList("ddlMerit", new SelectList(Model.listMerits, "Value", "Text"), new { style = "width:100px;height:31px" })
@Html.DropDownListFor(m => Model.listMerits, Model.listMerits, "--Select--");
最佳答案
试试这个
public static IEnumerable<SelectListItem> GetAllMerits()
{
using (DataContext ctx = new DataContext())
{
var results = (from m in ctx.MeritBadges
select new SelectListItem
{
Value = m.ID.ToString(),
Text = m.MeritBadgeName
}
).OrderBy(o => o.Text).ToArray(); // .ToArray() => materialize collection. After this data will be returned from database.
return new SelectList(results, "Value", "Text");
}
}
关于c# - MVC 5 DropDownList 说 DbContext 已释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39350511/