Caverman Caverman - 2 months ago 15
C# Question

MVC 5 DropDownList says DbContext is disposed?

I thought I was starting to understand how to use DDL in MVC but I guess I'm still not really getting their proper setup.

I have a DropDownList that I'm populating from Entity Framework and using a repository. I can debug through the code and see that the ViewModel is getting populated with the values but once I get to the View I get and error

"The operation cannot be completed because the DbContext has been disposed"
. I thought by the time I got to the View the DbContext was no longer needed anyway?

I've tried different combinations of Html.DropDownList and Html.DropDownListFor and each time I'm coming up with the same message. I'm sure this is something simple that I'm just not understanding but I've been looking over different examples and trying a couple different combinations without any luck.

This is my ViewModel

public class AssignCounselorViewModel
{
public IEnumerable<SelectListItem> listMerits { get; set; }

public int MeritSelectedId { get; set; }
}


This is my Controller:

public ActionResult AssignCounselor()
{
var viewModel = new AssignCounselorViewModel();
viewModel.listMerits = MeritCounselorRepository.GetAllMerits();

return View(viewModel);
}


This is my Repository:

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");
}
}


This is my View:

<div class="row">
<div class="col-md-12">
@Html.DropDownListFor(m => m.listMerits,
new SelectList(Model.listMerits, "Text", "Value"))
</div>
</div>


Here are some other combinations I've tried.

@Html.DropDownList("ddlMerit", new SelectList(Model.listMerits, "Value", "Text"), new { style = "width:100px;height:31px" })


@Html.DropDownListFor(m => Model.listMerits, Model.listMerits, "--Select--");

Answer

Try this

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"); 
    }
}
Comments