Part 34 Generating a dropdownlist control in mvc using HTML helpers
Why Stack Overflow recommends it
Stack Overflow users link it when they are learning or debugging DropDownList and ViewBag usage in ASP.NET MVC and want the tutorial's working example.
Recommended by 0 people across 0 different months, 2013 to 2016.
What it is
A short ASP.NET MVC tutorial from kudvenkat's MVC series (part 34) on generating a dropdown list with the DropDownList HTML helper. It shows hard-coded SelectListItem values first, then loads departments from a database with Entity Framework and passes a SelectList through the ViewBag.
What people said
Cites user79808 · 2013-08 · Stack Overflow · on “Dropdownlist in asp.net mvc technical working reference”
I have invested my few hours figuring out how to work with dropdownlists.. finally I have a working piece of code.. but I do not know how it works. [this video] In Controller. ViewBag.Breed = new SelectList(db.Breeds, "breed", "breed"); In view @Html.DropDownList("Breed", "Select Breed") How does it works??
Cites Juan Carlos Oropeza · 2016-03 · Stack Overflow · on “How HtmlHelper know data is on the ViewBag?”
I was watching a tutorial about HtmlHelper for DropDown [this video] Around min 8, he is reading the db to replace some hardcode values. To pass list of Departments from the controller, store them in "ViewBag" public ActionResult Index() { // Connect to the database SampleDBContext db = new SampleDBContext(); // Retrieve departments, and build SelectList ViewBag.Departments = new SelectList(db.Departments, "Id", "Name"); return View(); } Last step. Now in the "Index" view, access Departments list from "ViewBag" @Html.DropDownList("Departments", "Select Department") I dont see anything like strong type model on the view. So how the Helper know Departments refers to a value in the ViewBag?
Cites Dieglock · 2016-07 · Stack Overflow · on “@Html.DropdownList fails to save... There is no ViewData item of type 'IEnumerable' that has the key”
I have been dealing a day with the dropdowns at mvc 5 with c# and razor. Example, the one that works. A Hardcoded dropdown means no trouble. @Html.DropDownList("Example1", new List<SelectListItem> { new SelectListItem { Text= "1", Value = "1" }, new SelectListItem { Text = "2", Value = "2" } }, "Select") Problem comes when trying to pass the data from the model trough controller to the view. I have found many examples that suppose to work, they do display the dropdown, but fail when trying to save the data. Error is: There is no ViewData item of type 'IEnumerable' that has the key 'Example'. From this video [this video] the shorter one: @ controller public ActionResult Index() { MyDB db = new MyD