I'm new to ASP.NET core and razor page. I hav ecreated a button and assigned a page handler to delete the entry. When I'm trying to delete im getting a null reference error. When I run the code and click the button to delete an entry, im getting a null exception error
I want to know where I'm making mistake and some guidance to improve my coding. Thank you in advance for those who helped.
This is my index page
@page
@model BookList.Pages.BookPages.IndexModel
<form method="post">
@if (Model.Books.Count()>0)
{
<table class="table table-dark border">
<tr class="table-secondary">
@foreach (var book in Model.Books)
{
<tr>
<td>
@Html.DisplayFor(m => book.Name)
</td>
<td>
@Html.DisplayFor(m => book.Author)
</td>
<td>
<button class="btn btn-danger btn-sm" asp-page-handler="Delete" asp-route-id="@book.Id" onclick="return confirm('Are you sure you want to delete?')">Delete</button>
<a class="btn btn-success btn-sm" asp-route-id="@book.Id" asp-page="Edit">Edit</a>
</td>
</tr>
}
</table>
}
else
{
<p>No books available</p>
}
</form>
This is my page model
public IEnumerable<Book> Books { get; set; }
public async Task OnGet()
{
Books = await _dbContext.Books.ToListAsync();
}
public async Task<IActionResult> onPostDelete(int id)
{
var book = await _dbContext.Books.FindAsync(id);
if (book == null)
return NotFound();
_dbContext.Books.Remove(book);
await _dbContext.SaveChangesAsync();
return RedirectToPage("Index");
}
}
}
