Populate Data in DropDownList in Create Mode MVC 4

asp.net, asp.net-mvc, asp.net-mvc-4, c#, entity-framework

Solution

Change your get method "Create" as mentioned below :

public ActionResult Create()
{
    var languages = new List<Language>();
    using (MyDBContext db = new MyDBContext())
    {
        languages = db.Languages.ToList();
    }

    ViewBag.ID = new SelectList(languages, "ID", "Title");
    return View();
}

Now you can use DropDownListFor as mentioned below :

@Html.DropDownListFor(model => model.[PropertyName], (IEnumerable<SelectListItem>)ViewBag.ID)

Problem

I'm trying to populate data from table in DropDownList using MVC4. Trying to figure it out how to get all the languages' titles into the DropDown in the Edit mode. Models: ``` public class CategoryLanguage { public int ID { get; set; } public int LanguageID { get; set; } public string Title { get; set; } public string Description { get; set; } } public class Language { public int ID { get; set; } public string Title { get; set; } } ``` Controller: ``` public ActionResult Create() { using (MyDBContext db = new MyDBContext()) { ViewBag.ID = new SelectList(db.Languages, "ID", "Title"); return View(); } } // // POST: /Emp/Create [HttpPost] public ActionResult Create(CategoryLanguage newCatLang) { using (MyDBContext db = new MyDBContext()) { if (ModelState.IsValid) { db.CategoryLanguages.Add(newCatLang); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.ID = new SelectList(db.Languages, "ID", "Title", newCatLang.LanguageID); return View(newCatLang); } } ``` View: ``` @model MultilanguageCategories.CORE.Models.CategoryLanguage @{ ViewBag.Title = "Create"; } <h2>Add New Item</h2> @using (Html.BeginForm()) { @Html.ValidationSummary(true) @Html.DropDownList("ID", "--Select--") } ``` Trying to figure it out how to get all the languages' titles into the DropDown when creating new CategoryLanguage entity. The error says: "The operation cannot be completed because the DbContext has been disposed." and this line marked: @Html.DropDownList("ID", "--Select--")

Original source