In this article I will explain with an example, how to perform looping through Model Items in ASP.Net Core Razor Pages.
The Model data will be fetched using Entity Framework and then using a FOR EACH loop the Model items will be traversed and data will be displayed using HTML Table in ASP.Net Core Razor Pages.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Note: The Customers Table of the Northwind Database will be used in this project.
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
1. Once the package is successfully installed, create a Folder named Models in your project and then a new class by right clicking the Models folder and then click on Add and then New Item option of the Context Menu.
2. Create the following properties inside the Model class as shown below.
Note: In this article, only four Columns will be displayed and hence four properties are added to the class.
public class Customer
{
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Database Context
1. 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.
2. 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.
using Microsoft.EntityFrameworkCore;
using Razor_Entity_Framework.Models;
namespace Razor_Entity_Framework
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<Customer> Customers { get; set; }
}
}
Adding the Connection String inside AppSettings.json
The following Connection String setting has been added in the AppSettings.json file.
{
"ConnectionStrings": {
"MyConn": "Data Source=.\\SQL2017;Initial Catalog=Northwind;Integrated security=true"
}
}
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.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
namespace Razor_Entity_Framework
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
string conStr = this.Configuration.GetConnectionString("MyConn");
services.AddDbContext<DBCtx>(options => options.UseSqlServer(conStr));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
}
}
}
Razor PageModel (Code-Behind)
The Database Context is injected into the IndexModel class using Dependency Injection method.
Handler method for handling GET operation
Inside the Handler method that handles the GET calls, the Top 10 records are fetched from the Customers Table of the Northwind Database and returned to the Razor Page.
public class IndexModel : PageModel
{
private DBCtx Context { get; }
public IndexModel(DBCtx _context)
{
this.Context = _context;
}
public List<Customer> Customers { get; set; }
public void OnGet()
{
this.Customers = (from customer in this.Context.Customers.Take(10)
select customer).ToList();
}
}
Razor Page (HTML)
The HTML of Razor Page consists of an HTML Table.
A FOR loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@page
@model Razor_Entity_Framework.Pages.IndexModel
@using Razor_Entity_Framework.Models
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<h4>Customers</h4>
<hr/>
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerID</th>
<th>ContactName</th>
<th>City</th>
<th>Country</th>
</tr>
@foreach (Customer customer in Model.Customers)
{
<tr>
<td>@customer.CustomerID</td>
<td>@customer.ContactName</td>
<td>@customer.City</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads