I am currently making a small application with basic CRUD operations and I want to display all Books in my View. But when I call .Books
object it's written that:
'IndexModel' does not contain a definition for 'Books' and no accessible extension method 'Books' accepting a first argument of type 'IndexModel' could be found (are you missing a using directive or an assembly reference?)
Here is what I did so far:
Book Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD_Razor_2_1.Model
{
public class Book
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string ISBN { get; set; }
public string Author { get; set; }
}
}
ApplicationDbContext
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD_Razor_2_1.Model
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Book> Books { get; set; }
}
}
Index.html.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CRUD_Razor_2_1.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace CRUD_Razor_2_1.Pages.BookList
{
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _db;
public CreateModel(ApplicationDbContext db)
{
_db = db;
}
[BindProperty]
public Book Book { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPost()
{
if(!ModelState.IsValid)
{
return Page();
}
_db.Books.Add(Book);
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
}
}
And here when I want to call Model.Book.Count()
is where I get the error:
@page
@model IndexModel;
@{
}
<br />
<h2>Book List</h2>
<br />
<a asp-page="Create" class="btn btn-primary">Create New Book</a>
@if(Model.Books.Count() > 0)
{
}
else
{
}