How to Populate DropDownList from the Database in MVC

Step1

We need to put this code in the controller i.e IndexController

ViewBag.Categories = db.Categories.ToList();

Where db is a object of a database connection and categories is the name of the table

Step2

We also need to put the code in the cshtml page i.e IndexCshtml.

@Html.DropDownListFor(model => model.CategoryId, new SelectList(ViewBag.Categories, "CategoryId", "CategoryName"), "Select a Category")

Ebook Download
View all
Learn
View all