Header add

In this article we will discuss how to bind Dropdown List With Database in ASP.NET Core and Entity Framework.

Create a sample Database table that holds the information of departments.


Let's create a .NET Core MVC application using VS 2019 with targeting framework 3.1 ( You can do it according to your IDE and version). If you are wonder how to create a .NET Core application then follow the link how to create .NET Core application in VS 2019
Step-1 : Installing Package for Entity framework core From NuGet

To install the package just right click on the project and then select Manage NuGet package. Below dialog of NuGet Package Manager will pop up. In the browse tab, there is a search box, where you are required to type "Microsoft.EntityFrameworkCore.SqlServer" and just click Install button to install like below;

Step-2 : Add the connection string in appsettings.json file like below;
Step-3 : Add a model inside Models folder and map into database table
Step-4 : Add another class DataContext to use Entity framework code first approach

After adding a DataContext class, we are going to inherit DbContext class.After inheriting with DbContext, we are having a constructor, which takes DbContextOptions as an input parameter and also inherits base class constructor (: base(options)) [DbContext].

Step-5 : Now, we are going to add new Service in Startup.cs class to inject dependency.
                 Now, whenever you are going to use DataContext class, DbContext instance will be injected.

Add the connectionstring name as like in appsettings.json then inject the Datacontext as like above.

Step-6 : In HomeController.cs we are using constructor injection to get a dependency.

Step-7 : In Index.cshtml add the Department model and add the dropdown using Viewbag.Departments

Now save the application and run and you can see the output like below;

</> Find the Source Code in Github.com/CoreProgramm/

  In this tutorial we discussed how to Bind Dropdown List With Database in ASP.NET Core and Entity Framework. If have any question related to this topic then give your feedback.

You May Also Like...

Post a Comment

Previous Post Next Post