Binding Data To Dropdown List In ASP.NET Core MVC Web Application

Introduction

 
In this article I will explain how to populate a dropdown list from database values in ASP.NET Core MVC applications. An MVC application consists of model, view and controller. In this application I will create and scaffold a model to work with the database and retrieve data from SQL Server database. The controller will be responsible for selecting a view to be displayed to the user and provide necessary data model to retrieve and display data into the dropdown list from SQL Server database. The controller manages how the application would respond to the get request made to SQL Server database.
 

Creating ASP.NET Core MVC web applications

 
Before writing the coding part of ASP.NET Core MVC application, first we need to create a table in SQL Server database so that values available in the database can be retrieved and bind to dropdown list in the ASP.NET Core MVC web application. 
 
The table can be created with the help of the following SQL query.
  1. create table dbo.country  
  2. (  
  3.   Cid int not null identity(1,1) primary key,  
  4.   Cname varchar(100)  
  5. );  
The database table looks like the following
 
 
Now we will create a new ASP.NET Core MVC application as follows.
 
 
 
Here we will select ASP.NET Core Web application, provide a project name and select model-view-controller as web application template.
 
Now we will be adding a connection string inside appsettings.json to connect to SQL Server database.
  1. {  
  2.   "ConnectionStrings": {  
  3.     "Myconnection""Data Source=DESKTOP-QGAEHNO\\SQLEXPRESS;Initial Catalog=profiledb;Integrated Security=True"  
  4.   },  
  5.   "Logging": {  
  6.     "LogLevel": {  
  7.       "Default""Information",  
  8.       "Microsoft""Warning",  
  9.       "Microsoft.Hosting.Lifetime""Information"  
  10.     }  
  11.   },  
  12.   "AllowedHosts""*"  
  13. }  
The next step is to add a class named Country inside models folder. Inside Country class, we will be defining two properties, Cid and Cname, to retrieve and bind database country column values to dropdown list controls.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace BindingData.Models  
  8. {  
  9.     public class Country  
  10.     {  
  11.         [Key]  
  12.         public int Cid { getset; }  
  13.                   
  14.         public string Cname { getset; }  
  15.     }  
  16. }  
Here Cid is a primary key which is of integer type and Cname is of type string.
 
Now we will define another class named ApplicationUser to add a DbContext to connect and query to the database.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.EntityFrameworkCore;  
  6.   
  7. namespace BindingData.Models  
  8. {  
  9.     public class ApplicationUser : DbContext  
  10.     {  
  11.         public ApplicationUser(DbContextOptions<ApplicationUser> options) : base(options)  
  12.         {  
  13.   
  14.         }  
  15.         public DbSet<Country> country { getset; }  
  16.     }  
  17. }  
Here we are adding the DbSet property to query the database.
 
Now within startup.cs class, we need to add services for application user class and connection string inside configureServices method.
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddDbContext<ApplicationUser>(options => options.UseSqlServer(Configuration.GetConnectionString("Myconnection")));  
  4.             services.AddControllersWithViews();  
  5.         }  
Now we will be adding a controller named Dropdown to define action methods required to make a get request to the server, retrieve data and bind the data to the dropdown list control.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.EntityFrameworkCore;  
  7. using BindingData.Models;  
  8.   
  9.   
  10. namespace BindingData.Controllers  
  11. {  
  12.     public class DropdownController : Controller  
  13.     {  
  14.         private readonly ApplicationUser _auc;  
  15.   
  16.         public DropdownController(ApplicationUser auc)  
  17.         {  
  18.             _auc = auc;  
  19.         }  
  20.         public IActionResult Index()  
  21.         {  
  22.             List<Country> cl = new List<Country>();  
  23.             cl = (from c in _auc.country select c).ToList();  
  24.             cl.Insert(0, new Country { Cid = 0, Cname = "--Select Country Name--" });  
  25.             ViewBag.message = cl;  
  26.             return View();  
  27.         }  
  28.     }  
  29. }  
The above code is to retrieve data from SQL Server database and bind the data to dropdown list control in ASP.NET Core MVC application.
 
The next step is to add a view page for the create action method defined inside the controller class.
 
To add a view page, select the respective action method, right click and click on add view option at the top.
  1. @model BindingData.Models.Country  
  2. @{  
  3.     ViewData["Title"] = "Index";  
  4. }  
  5.   
  6. <h1>Binding data into Dropdown list</h1>  
  7. <hr />  
  8. <select asp-for="Cid" asp-items="@(new SelectList(ViewBag.message,"Cid","Cname"))"></select>  
Inside create.cshtml view page, we have defined a dropdown list control to retrieve data from database and bind it to the dropdown list control.
 

Output

 
The output of the web application is as follows:
 
 

Summary

 
In this article, I explained how to populate a dropdown list from database values in ASP.NET Core MVC application. I created model classes to define properties for the dropdown list control and dbset properties to connect to database. A controller has been created which selects a view to be displayed to the user and provides the necessary data model to retrieve data from the SQL Server database. A view page has been created for index action method in which dropdown list control has been designed. Proper coding snippets along with output have been provided for each and every part of the application.