Populate Data in DropDownList in Create Mode MVC 4

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

Question

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

1
5
1/31/2014 10:59:55 AM

Accepted Answer

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)
3
1/31/2014 12:55:55 PM

Popular Answer

you're close...

You need to Add the languages select list to the viewbag (which you've already done, but with a badly named key)

ie: ViewBag.LanguagesList = new SelectList(db.Languages, "ID", "Title");

if you want an empty field that's easy enough too:

var langs = db.Languages.ToList().ConvertAll(x => new SelectListItem() { Value = x.ID, Text = x.Title });
langs.Insert(0, new SelectListItem() { Value = "", Text = "--Select--" });
ViewBag.LanguagesList = langs;

The DropdownList should be for a property in the model.

@Html.DropDownListFor(m => m.LanguageID, (IEnumerable<SelectListItem>)ViewBag.LanguagesList)

As it looks like you are using an Entity Framework class as your model you need to ensure the context is not disposed before the view is rendered.

As Per Microsoft's example link instantiate the context at the top of the controller, and drop the using statement in the Create method.

ie :

public class LanguageCategoryController : Controller
{
    MyDBContext db = new MyDBContext();

    public ActionResult Create()
    {
            ViewBag.LanguagesList = new SelectList(db.Languages, "ID", "Title");
            // or replace the above line with the other example above
            // if you want the empty "--select--" option

            return View();           
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow