我目前正在制作一个具有基本CRUD操作的小型应用程序,并且我想在View中显示所有Book。但是,当我调用.Books
对象时,它写为:
'IndexModel'不包含'Books'的定义,并且找不到可以接受的扩展方法'Books'接受类型为'IndexModel'的第一个参数(您是否缺少using指令或程序集引用?)>
这是我到目前为止所做的:
图书模型
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");
}
}
}
在这里我想打电话给Model.Book.Count()
时,我得到了错误:
@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
{
}