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: [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: //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.