In this article we will discuss Display data in GridView (Grid) in ASP.Net Core.
Here we will explain how to configure Entity Framework and connect to SQL Server database and displayed in View in ASP.Net Core MVC..
Before start this article, please visit our previous article Populating DropDownList inside Razor Pages in ASP.Net Core MVC
Database
Downloading Entity Framework Core
You will need to install the Microsoft.EntityFrameworkCore.SqlServer package using the following command.
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.1.1
Model
Let's create a class in Models folder like below.
Database Context
Now you will need to add a new class to your project by right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.
Inside the class, first inherit the EntityFrameworkCore namespace and then inherit the DbContext class.
Then using Dependency Injection, a Constructor is created DbContextOptions are passed as parameter and also the Constructor of base class i.e. DbContext class is inherited.
Finally, a DbSet Collection property of Customer Model class is created, which will be later used for holding the Data fetched from SQL Server Database Table.
Adding the Connection String inside AppSettings.json
The following Connection String setting has been added in the AppSettings.json file.
Configuring Database Context in Startup class
Inside the Startup class, the IConfiguration is injected in the Startup class and assigned to the private property Configuration.
Then the Connection String is read from the AppSettings.json file and is used to add the DbContext service.
Controller
Inside the Index Action method, the Top 10 records are fetched from the States Table.
View
Inside the View, in the very first line the State Entity is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the State records.
Output
When run the application we can see the output like below.
Post a Comment