Articles → ASP.NET CORE → Delete Records In Asp.Net Core

Delete Records In Asp.Net Core






Steps




  1. Add a delete button on the table
  2. Add a confirm message on the delete button
  3. Add delete handler

Code




@page
@model BookManagementSystem.Pages.Books.BooksModel
@{
    ViewData["Title"] = "Books";
}


<h1>Books</h1><form method="post"><div class="col-4"><a asp-page="Create" class="btn btn-info form-control text-white"> Create new book</a></div><div class="col-12 m-1">
        @if (Model.Books.Count() > 0)
        {
            
		<table border="1"><tr><th>
                        Name
                    </th><th>
                        Author
                    </th><th>
                        Edit
                    </th></tr>
                @foreach (var item in Model.Books)
                {
                    
			<tr><td>
                            @Html.DisplayFor(m => item.Name)
                        </td><td>
                            @Html.DisplayFor(m => item.Author)
                        </td><td><a asp-page="Edit" asp-route-id="@item.Id" class="btn btn-success">Edit</a><button asp-page-handler="Delete" asp-route-id="@item.Id" onclick="return confirm('Are you sure you want to delete?');" class="btn btn-danger">Delete</button></td></tr>
                }

            
		</table>
        }
    
	</div></form>




using BookManagementSystem.Model;
using Microsoft.AspNetCore.Mvc;
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();
    }

    public async Task < IActionResult > OnPostDelete(int id) {
      Book MyBook = await _db.Book.FindAsync(id);

      if (MyBook == null) {
        return NotFound();
      }
      _db.Book.Remove(MyBook);
      await _db.SaveChangesAsync();
      return RedirectToPage("Books");
    }
  }
}





Output


Picture showing a page to delete the record in asp.net core
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, April 1, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250