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.
- create table dbo.country
- (
- Cid int not null identity(1,1) primary key,
- Cname varchar(100)
- );
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.
- {
- "ConnectionStrings": {
- "Myconnection": "Data Source=DESKTOP-QGAEHNO\\SQLEXPRESS;Initial Catalog=profiledb;Integrated Security=True"
- },
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "AllowedHosts": "*"
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using System.ComponentModel.DataAnnotations;
-
- namespace BindingData.Models
- {
- public class Country
- {
- [Key]
- public int Cid { get; set; }
-
- public string Cname { get; set; }
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.EntityFrameworkCore;
-
- namespace BindingData.Models
- {
- public class ApplicationUser : DbContext
- {
- public ApplicationUser(DbContextOptions<ApplicationUser> options) : base(options)
- {
-
- }
- public DbSet<Country> country { get; set; }
- }
- }
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.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationUser>(options => options.UseSqlServer(Configuration.GetConnectionString("Myconnection")));
- services.AddControllersWithViews();
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using BindingData.Models;
-
-
- namespace BindingData.Controllers
- {
- public class DropdownController : Controller
- {
- private readonly ApplicationUser _auc;
-
- public DropdownController(ApplicationUser auc)
- {
- _auc = auc;
- }
- public IActionResult Index()
- {
- List<Country> cl = new List<Country>();
- cl = (from c in _auc.country select c).ToList();
- cl.Insert(0, new Country { Cid = 0, Cname = "--Select Country Name--" });
- ViewBag.message = cl;
- return View();
- }
- }
- }
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.
- @model BindingData.Models.Country
- @{
- ViewData["Title"] = "Index";
- }
-
- <h1>Binding data into Dropdown list</h1>
- <hr />
- <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.