Articles → ASP.NET CORE → Get The List Of Records Using The Get API And Delete The Record Using Delete API In Asp.Net Core

Get The List Of Records Using The Get API And Delete The Record Using Delete API In Asp.Net Core






Scenario




Picture showing the schema of the books table
Click to Enlarge


Implementation




  1. Create a folder "Controllers".
  2. Right-click on the folder "Controllers" and click on the "Add" → "Controller.."
  3. Picture showing the context menu for adding a Controller
    Click to Enlarge

  4. A popup window will appear. From the popup window, select the option "MVC Controller - Empty".
  5. Picture showing the window to add MVC Controller - Empty
    Click to Enlarge

  6. Click on the "Add" button. Another window will appear to enter the controller name.
  7. Enter the name as "BookController" and click on the "Add" button.
  8. Picture showing the window to enter the controller name
    Click to Enlarge

  9. Inside the controller, write the following code.
  10. using BookManagementSystem.Model;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace BookManagementSystem.Controllers {
      [Route("api/Books")]
      [ApiController]
      public class BookController: Controller {
        private readonly ApplicationDbContext _db;
    
        public BookController(ApplicationDbContext db) {
          _db = db;
        }
    
        [HttpGet]
        public IActionResult GetAll() {
          return Json(new {
            data = _db.Book.ToList()
          });
        }
    
        [HttpDelete]
        public async Task < IActionResult > Delete(int id) {
          var book = await _db.Book.FirstOrDefaultAsync(x => x.Id == id);
    
          if (book == null) {
            return Json(new {
              Success = false, message = "Error while deleting"
            });
          }
          _db.Book.Remove(book);
          await _db.SaveChangesAsync();
          return Json(new {
            Success = true, message = "Delete Successful"
          });
    
        }
      }
    }



Changes In Startup.Cs




  1. Add the following code in "ConfigureServices" method.
  2. services.AddControllersWithViews();


  3. In the "Configure" method, modify the code to add the endpoint.
  4. app.UseEndpoints(endpoints => {
      endpoints.MapControllers();
      endpoints.MapRazorPages();
    });



Changes In "Books.Cshtml"




@page @model BookManagementSystem.Pages.Books.BooksModel @{ ViewData["Title"] = "Books"; }
<h1>Books</h1><form method="post"><table id="DT_Load" class=" table table-striped table-bordered" style="width:100%"><thead><tr><th>Name</th><th>Author</th><th>Edit</th><th>Delete</th></tr></thead><tbody></tbody></table></form> @section Scripts {
<script>
$(document).ready(function() {
	$.ajax({
		"url": "/api/books",
		"type": "GET",
		"datatype": "json",
		success: function(result) {
			$.each(result.data, function(index, element) {
				$('#DT_Load tbody').append('<tr class="child"><td>' + element.name + '</td><td>' + element.author + '</td>' + `<td class="text-center"><a href="#" class='btn btn-success text-white' style='cursor:pointer; width:70px;'>
                                    Edit
                            </a></td><td><a class='btn btn-danger text-white' style='cursor:pointer; width:70px;'
                                 onclick="Delete('/api/books?id=` + element.id + `')">
                                Delete
                            </a></td></tr>`);
			});
		}
	});
});

function Delete(url) {
	if(confirm("Are you sure, you want to delete this book?")) {
		$.ajax({
			"url": url,
			"type": "DELETE",
			"datatype": "json",
			success: function(result) {
				alert("Book Deleted");
				location.reload(true);
			}
		});
	}
}
</script> }





Output




Picture showing the list of records on page load
Click to Enlarge



Picture showing the confirm message when delete button is clicked
Click to Enlarge



Picture showing the message when record is deleted
Click to Enlarge



Picture showing the list of records once a record is deleted
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, April 3, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250