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








Picture showing the context menu for adding a Controller

Click to Enlarge



Picture showing the window to add MVC Controller - Empty

Click to Enlarge





Picture showing the window to enter the controller name

Click to Enlarge



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






services.AddControllersWithViews();




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