Last post Nov 17, 2016 06:33 PM by rogersbr
Nov 16, 2016 08:21 PM|rogersbr|LINK
The goal is to use the Controller to fill a Dropdown list then pass that into Viewbag, then reference this in the view.
Here is the potential solution from an online page, https://aspdotnetcodehelp.wordpress.com/2015/04/12/how-to-load-dropdownlist-from-database-in-mvc-or-populate-dropdownlist-in-mvc-from-database/
If you already have connection string configured then you can select that from the available list.
If you don’t have the connection string configured then use the New Connection option and create the connection
You can get more details about how to use DatabaseFirst
approach from this link.
Once the needed model files are generated now we need to create the code to get the data from database and then pass it to view for dropdownlist.
You can use the below code to get the value from database and pass it to ViewBag
public ViewResult Index()
//Create db context object here
AdventureWorksDbContext dbContext = new AdventureWorksDbContext();
//Get the value from database and then set it to ViewBag to pass it View
IEnumerable<SelectListItem> items = dbContext.Employees.Select(c => new SelectListItem
Value = c.JobTitle,
Text = c.JobTitle
ViewBag.JobTitle = items;
Have it working, they left out an important part. when you generate the reference? it creates a link within
The ContosoModel.Context.cs file contains a class that derives from the DbContext class, and provides a property for each model class that corresponds to a database table. The Course.cs,Enrollment.cs,
and Student.cs files contain the model classes that represent the databases tables. You will use both the context class and the model classes when working with scaffolding.
find the (yourname)Context.cs file and find the dbcontext NAME. thats the name you must reference...
Nov 17, 2016 07:10 AM|Jean Sun|LINK
I read the link and I find one mistake in this link, when you assign the values in ViewBag to the DropDownList the following code is the correct one.
@Html.DropDownList("JobTitle", (SelectList)ViewBag.JobTitle, "Select a Value")
And what's the problem are you facing now?
Nov 17, 2016 06:33 PM|rogersbr|LINK
Well it now works. Once I used the correct reference to retreive the database contents? then i could do the rest, now the dropdowns work great; but i could not delete my original question and just left it