Population @ Html.DropDownList with list <string> using MVC

I am trying to populate a @ Html.DropDownList list with a list using MVC and Razor. Bellow is my code for the controller. Therefore, I need to select a list from my ViewBag and fill out the drop down list.

public ActionResult Register() { sparklingEntities context = new sparklingEntities(); var query = (from discs in context.Disciplines select discs).ToList(); List<string> listOfDiscs = new List<string>(); foreach (var item in query) { listOfDiscs.Add(item.Discipline); } ViewBag.ListOfDisciplines = listOfDiscs; return View(); } 

Thanks for the help.

+7
source share
3 answers

If this property is in the editor for your model property:

 @Html.DropDownList("", new SelectList(ViewBag.ListOfDisciplines, Model)) 
+11
source
 //Increase performance by Eliminating foreach loop! public ActionResult Register() { sparklingEntities context = new sparklingEntities(); var query = (from discs in context.Disciplines select discs.Discipline); // change this line as discs.Discipline ViewBag.ListOfDisciplines = listOfDiscs; return View(); } 
+1
source

the value does not get stored in the database. see where I get the error ...

  public ActionResult Role(Role_Master_Table t) { FTSdatabaseEntities dc = new FTSdatabaseEntities(); { //ViewBag.Status_Description = new SelectList(dc.Status_Master_Table, "StatusId", "Status_Description", "Remarks"); var query = (from Status_Description in dc.Status_Master_Table select Status_Description).ToList(); List<string> listOfDiscs = new List<string>(); foreach (var item in query) { listOfDiscs.Add(t.Status); dc.Role_Master_Table.Add(t); dc.SaveChanges(); } ViewBag.Status_Description = listOfDiscs; return View(); } 
0
source

All Articles