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!

The resource has not been reviewed by Editors yet. Readers are advised to use their best judgement before accessing this resource.
This resource will be reviewed shortly.
If you think this resource contain inappropriate content, please report to webmaster.
I'm going to populate or fill my dropdown using a viewbag. You can use ViewData or TempData as well.

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!


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: