Articles → ASP.NET CORE → Get the list of records from the database in asp.net core

Get the list of records from the database in asp.net core






Database table




Picture showing the table schema of the book table

Click to Enlarge


Code




using BookManagementSystem.Model;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BookManagementSystem.Pages.Books {
  public class BooksModel: PageModel {
    private readonly ApplicationDbContext _db;
    public BooksModel(ApplicationDbContext db) {
      this._db = db;
    }

    public IEnumerable < Book > Books {
      get;
      set;
    }

    public async Task OnGet() {
      Books = await _db.Book.ToListAsync();
    }
  }
}




@page 
@model BookManagementSystem.Pages.Books.BooksModel 
@{ ViewData["Title"] = "Books"; }
<h1>Books</h1>
<form method="post">@if (Model.Books.Count() > 0) {
	<table border="1">
		<tr>
			<th>Name</th>
			<th>Author</th>
		</tr>@foreach (var item in Model.Books) {
		<tr>
			<td>@Html.DisplayFor(m => item.Name)</td>
			<td>@Html.DisplayFor(m => item.Author)</td>
		</tr>}</table>}</form>





Output


Picture showing the list of records from the book table

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, March 31, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250