gpt4 book ai didi

c# - MVC 5 DropDownList 说 DbContext 被处理了吗?

转载 作者:行者123 更新时间:2023-11-30 21:46:18 25 4
gpt4 key购买 nike

<分区>

我以为我开始了解如何在 MVC 中使用 DDL,但我想我仍然没有真正获得它们的正确设置。

我有一个从 Entity Framework 填充并使用存储库的 DropDownList。我可以通过代码进行调试,并看到 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--");

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com