How to delete a record in ASP.NET Core without page reload


In this article, we'll explore how to delete rows from an HTML table within an ASP.NET Core application without a page refresh. We can accomplish this by using either Entity Framework Core or ADO.NET along with jQuery. 

Let's delve into the process of deleting records from the database in an ASP.NET MVC application without causing a page reload.

Step 1:

Create a Model: Let's Define the Professor model with fields Id, FirstName, LastName, and Email.

public class Professor
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}
Step 2: Set up DbContext: Create a ProfessorDbContext class that inherits from DbContext and configure it with the appropriate connection string and DbSet for the Professor model.
public class ProfessorDbContext : DbContext
{
    public ProfessorDbContext(DbContextOptions<ProfessorDbContext> options) : base(options)
    {
    }

    public DbSet<Professor> Professors { get; set; }
}
Step 3: 
Create Controller: Create a controller with actions to handle HTTP requests. For example, we can have an action to delete a professor record.
[Route("api/[controller]")]
[ApiController]
public class ProfessorController : ControllerBase
{
    private readonly ProfessorDbContext _context;

    public ProfessorController(ProfessorDbContext context)
    {
        _context = context;
    }

    // Action to get the list of professors
    [HttpGet]
    public async Task<IActionResult> GetProfessors()
    {
        var professors = await _context.Professors.ToListAsync();
        return Ok(professors);
    }
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteProfessor(int id)
    {
        var professor = await _context.Professors.FindAsync(id);
        if (professor == null)
        {
            return NotFound();
        }

        _context.Professors.Remove(professor);
        await _context.SaveChangesAsync();

        return NoContent();
    }
}
Step 4: 
Client-side code(View) : Here is the jQuery code to send an AJAX request to the API endpoint for deleting a professor record without reloading the page.
//Display a list of professors with a delete button for each professor

<div id="professor-list">
    <!-- Loop through professors and display them -->
    @foreach (var professor in Model)
    {
        <div id="[email protected]">
            <span>@professor.FirstName @professor.LastName - @professor.Email</span>
            <button class="delete-btn" data-id="@professor.Id">Delete</button>
        </div>
    }
</div>


$(document).ready(function() {
    $(".delete-btn").click(function() {
        var professorId = $(this).data("id");
        
        $.ajax({
            url: "/api/Professor/" + professorId,
            type: "DELETE",
            success: function(result) {
                // Handle success, e.g., remove the deleted record from the UI
                $("#professor-" + professorId).remove();
            },
            error: function(xhr, status, error) {
                // Handle error
                console.error(error);
            }
        });
    });
});
When a user clicks on the delete button linked to a professor row: We send a DELETE AJAX request to the server-side endpoint connected with the DeleteProfessor action in the ProfessorController. 

In the jQuery AJAX success callback function, we remove the HTML table row representing the deleted professor from the Document Object Model (DOM), providing a smooth user experience without requiring a page reload.