How to Delete Images in ASP.NET Core MVC

SPONSOR AD

How to Delete Images in ASP.NET Core MVC

In this article, I will discuss How to Delete Images in ASP.NET Core MVC Application with Examples from Both Databases and File Systems. Please read our previous article discussing How to Display Images in ASP.NET Core MVC Application with Examples. Let’s continue with the application we worked on in previous articles.

How to Delete Images from Both Folders and Databases in ASP.NET Core MVC

Deleting images from both a folder (file system) and a database in an ASP.NET Core MVC application involves two main steps: removing the file from the file system and then deleting the corresponding record from the database.

Set Up Your Controller Action

Create an action method in your controller that will handle the deletion. This method should take an identifier (such as an image ID) as a parameter. So, add the following action method to the FileUpload Controller.

[HttpPost]
public async Task<IActionResult> DeleteImage(int id)
{
    //First check whether Id exists in the database
    EFCoreDbContext _context = new EFCoreDbContext();
    var image = await _context.Files.FirstOrDefaultAsync(f => f.Id == id);
    if (image == null)
    {
        // Handle the case where the image is not found
        return NotFound();
    }

    // Delete the file from the file system
    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", image.FileName);
    if (System.IO.File.Exists(filePath))
    {
        System.IO.File.Delete(filePath);
    }

    // Delete the record from the database
    _context.Files.Remove(image);
    await _context.SaveChangesAsync();

    return RedirectToAction("ShowImages"); // Redirect to the list of images page
}

In this code:

SPONSOR AD
  • The method searches for the image in the database using the provided ID.
  • If the image is found, it constructs the file path and deletes it from the file system.
  • It then removes the image record from the database and saves the changes.
Add a Delete Button or Link in the View

In your view, where you list the images, add a button or link for each image to trigger the deletion. This could be part of a form that posts to your delete action. So, modify the ShowImages.cshtml view as follows.

@model IEnumerable<FileModel>
@{
    ViewData["Title"] = "ShowImages";
}

<h1>Uploaded Images</h1>

<div class="row">
    <div class="col-md-4">
        @foreach (var image in Model)
        {
            <img src="@Url.Action("GetImage", new { id = image.Id })" width="200" height="200" alt="Image Not Availanle" class="img-fluid" />
            <form method="post" asp-action="DeleteImage" asp-controller="FileUpload" asp-route-id="@image.Id">
                <input type="hidden" name="id" value="@image.Id" />
                <button type="submit" class="text-danger">Delete</button>
            </form>
        }
    </div>
</div>

Now, run the application, go to the ShowImages page, and click on the Delete button as shown in the below image:

How to Delete Images in ASP.NET Core MVC Application with Examples

Once you click on the Delete button, it should delete the image from the File System and the database.

Important Notes:
  • Validation: Make sure to validate the user’s authorization to delete the image. You don’t want unauthorized users to be able to delete images.
  • Error Handling: Implement proper error handling for cases like the file or database record not existing.
  • Database Transactions: Consider using database transactions to ensure that both the file deletion and the database update occur successfully.
  • Backup Considerations: Be cautious with deletion operations. Once a file is deleted from the server, it cannot be easily recovered. You might want to implement a “soft delete” or archive feature instead of immediate deletion.
  • Asynchronous Operations: The example uses asynchronous operations (async/await) for database access and should be used especially when dealing with I/O operations.

In the next article, I will discuss How to Upload Multiple Files in ASP.NET Core MVC Application with Examples. In this article, I try to explain How to Delete Images in ASP.NET Core MVC Application with Examples. And I hope you enjoy this How to Delete Images in ASP.NET Core MVC article.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *