ASP.NET Core Razor Page not displaying database records even though they exist

ASP.NET Core Razor Page not displaying database records even though they exist

I'm trying to build a basic Razor Pages application that displays a list of books from a SQLite database. I used Entity Framework Core to scaffold the model and database context, and I confirmed that the database has data by checking with DB Browser for SQLite.

However, when I navigate to /Books, the page renders, but no books are displayed.

Here's my code:

Models/Book.cs:

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

Pages/Books/Index.cshtml.cs:

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using MyApp.Data;

public class IndexModel : PageModel
{
    private readonly MyAppContext _context;

    public IndexModel(MyAppContext context)
    {
        _context = context;
    }

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

    public void OnGet()
    {
        var books = _context.Books.ToList();
    }
}

Pages/Books/Index.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Book List";
}

<h1>Book List</h1>

<ul>
@foreach (var book in Model.Books)
{
    <li>@book.Title by @book.Author</li>
}
</ul>

I expected the list of books to appear on the page, but nothing is shown. The page loads fine without any errors.

I confirmed the database is populated using DB Browser, restarted the development server, and double-checked the model and context classes. Still, no data is rendered on the page.

I want the /Books Razor page to show all the books stored in the database.

Answer

You have a public property Books, which is exposed to the Razor file via its Model property. However, you don't assign it a value in the OnGet method. Instead, you assign a value to a local variable.

Change the OnGet code as follows:

public void OnGet()
{
    Books = _context.Books.ToList();
}

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions