Populate Data in DropDownList in Create Mode MVC 4

10,140

Solution 1

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)

Solution 2

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();           
    }
}
Share:
10,140
Stiliyan Vasilev
Author by

Stiliyan Vasilev

Updated on June 13, 2022

Comments

  • Stiliyan Vasilev
    Stiliyan Vasilev almost 2 years

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