Bind a DropDownList in ASP.NET Core
Problem definition: We need to bind table data to a DropDownList in an ASP.NET Core application. For example, we have a Country master table and need to show the countries in a drop-down list.
Below is the step-by-step process, explained in detail, so that you can bind a DropDownList in your application.
Step 1: Create a project in Microsoft Visual Studio
Select the project type ASP.NET Core Web App (Model-View-Controller).
Enter the name of your project.
Choose a suitable framework version and tick the Configure for HTTPS checkbox.
Your Solution Explorer looks like the image below.
Step 2: Install the required packages from the NuGet Package Manager
Select Microsoft.EntityFrameworkCore.SqlServer with a compatible version and install it.
Select Microsoft.EntityFrameworkCore.Tools with a compatible version and install it.
Select Microsoft.EntityFrameworkCore with a compatible version and install it.
You can check the installed packages, as shown in the image below.
Step 3: Create a Country model class for binding the drop-down list from the database.
public class Country
{
[Key]
public int CountryId { get; set; }
public string CountryName { get; set; }
} Step 4: Create an AppDbContext class and add the Country model class as a DbSet, as shown in the image and code below.
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Country> tblCountries { get; set; }
}
Step 5: Define the connection string in the appsettings.json file, as shown in the image below.
Step 6: Register the DbContext in the Program.cs file, as shown in the image below.
Step 7: Run the Add-Migration "FirstMigration" command, as shown in the image below.
Step 8: Run the Update-Database command, as shown in the image below.
After running the migration commands above, you can see a new Migrations folder in the solution, with an auto-generated FirstMigration class, as shown in the image below.
After running the migration commands above, you can see the new tables in the database, along with the auto-generated migration history table, as shown in the image below.
Step 9: Create a controller named TestController with an action method named Index, as shown in the code below.
public class TestController : Controller
{
private readonly AppDbContext db;
public TestController(AppDbContext _db)
{
db = _db;
}
public IActionResult Index()
{
var dropdownItems = db.tblCountries.ToList();
ViewBag.Country = new SelectList(dropdownItems, "CountryId", "CountryName");
return View();
}
}
Step 10: Create a view and write the HTML code below in it, as shown in the image.
Now run the application; you will get the output shown in the image below.