Usage of Dropdownlist using ASP.NET Core MVC with Database
This article mainly for the persons if they are struggling to populate a dropdownlist with some items from database.
Initially I faced a problem to populate dropdownlist in my view using MVC. Hence posting this article as a quick reference!
I'm going to populate or fill my dropdown using a viewbag. You can use ViewData or TempData as well.
Steps:
1) Define your viewBag in controller:
// GET: Product/Create
public IActionResult Create()
{
ViewBag.Categorynames = _context.Category.ToList();
//This is my viewbag
return View();
}
assume that my _context.Category is having CategoryId and CategoryName as key values meaning my database is having a table name as Category with two columns as CategoryId and CategoryName.
2) In your corresponding View you can define dropdownlist as below:
Above code will generate a dropdown list as below:
When you select CategoryName corresponding CategoryId value will be saved in database.
Please post your comments....
Happy coding!
Venkata