Welcome to RewaTechForge.com. Feel free to have a look around and leave a comment.

Meta

In this post, we’ll walk you through the basic process of creating a dynamic picture gallery where users can upload, view, and remove pictures. This project will utilize ASP.NET Core MVC for the front end, allowing for seamless integration with the entity framework backend.

Prerequisites and Tools:

Before we dive in, make sure you have the following prerequisites and tools installed:

  • Basic understanding of C# programming language and ASP.NET Core MVC framework.
  • Visual Studio IDE or Visual Studio Code.
  • .NET Core SDK.
  • Entity Framework Core for database operations.
  • Basic knowledge of HTML, CSS, and JavaScript.

Start a new solution

  1. Start Visual Studio 2022
  2. Click on Create A New Project
  3. In the Create A New Project Dialog, search for the  Asp.Net Core Web App (Model-View-Controller
  4. In the Configure your new project dialog, enter a name for you project name and click on Next.

 Install Nuget packages

To install the DB provider NuGet package, right click on the project in the Solution Explorer in Visual Studio and select Manage NuGet Packages. (or select on the menu: Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution).

  1. Choose the provider package for the database you want to access. In this case select Microsoft.EntityFrameworkCore.SqlServer for MS SQL Server as shown above. (make sure that it has the .NET symbol, and the Author is Microsoft). Click Install to start the installation.
  2. Install-Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore

This middleware helps to detect and diagnose errors with EF Core migrations.

  • Install EF Core Tools

Along with the DB provider package, you also need to install EF tools- Microsoft.EntityFrameworkCore.Tools

to execute EF Core commands. These make it easier to perform several EF Core-related tasks in your project at design time, such as migrations, scaffolding, etc.

You can install either through nugget package manager or through nugget package console.

Model-View-Controller Setup

Add the Model

Right click on the Model Folder and add a new class called picture.

PUBLIC CLASS PICTURE
{
    [KEY]
    PUBLIC INT PICTUREID { GET; SET; }

    [REQUIRED]
    PUBLIC STRING TITLE { GET; SET; }

    [REQUIRED]
    PUBLIC BYTE[] IMAGEDATA { GET; SET; }

    [REQUIRED]
    PUBLIC STRING CONTENTTYPE { GET; SET; }

}

In the Picture Class the ImageData property is used to store the binary data of the image, and the ContentType property is used to store the MIME type of the image. With these changes, you can store the pictures directly in the database.

The Picture model allows you to use Entity Framework Core to create a database schema for storing pictures.

Add the DBContext Class

Right click on the model class and add a new class. Rename the class as PictureContext. Replace the picture context class with the code below. Make sure to replace the namespaces.

using Microsoft.EntityFrameworkCore;

namespace MVCLearn.Models
{
    public class PictureContext:DbContext
    {
        public PictureContext( DbContextOptions<PictureContext> options): base(options) 
        { 
        }
        public DbSet<Picture> Pictures { get; set; }
    }
}

In the above code, PictureContext is the context class that inherits from DbContext.

The constructor takes DbContextOptions<PictureContext> as a parameter, which is typically injected by the dependency injection container.

Inside the constructor, base(options) is called to pass the options to the base DbContext class.

The Pictures property represents a DbSet for the Picture entity, allowing you to perform CRUD operations on the Picture entity using Entity Framework.

Make sure to replace Picture with the name of your entity class representing the picture entity.

Next you will need to register your DbContext in the program.cs file to register it with dependency injection.

Register the DBContext

ASP.NET Core includes dependency injection. Services, such as the EF database context, are registered with dependency injection during app startup. Components that require these services, such as MVC controllers, are provided these services via constructor parameters. The controller constructor code that gets a context instance is shown later in this tutorial.

Place just before the app instantiation with the builder.build()

builder.Services.AddDbContext<PictureContext>(options =>
            {
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
                // Replace "DefaultConnection" with your actual SQL Server connection string name from appsettings.json
            });

Open the appsettings.json file and add a connection string as shown in the following markup:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=PictureDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Add the Controller

Right click on the Controller folder, point to Add and click on controller.

In the Add New Scaffolded Item dialog, select MVC Controller-Empty and click on Add.

Enter a name for the controller in the Add New Item Dialog

The controller provides CRUD functionality for managing pictures in the application.

It includes methods for displaying, uploading, and removing pictures.

The methods interact with the database through the PictureContext instance injected via dependency injection.

Additionally, the controller handles file upload using ASP.NET Core’s built-in IFormFileCollection type and saves the uploaded files as binary data in the database.

Import necessary namespaces for working with Azure, ASP.NET Core MVC, Entity Framework Core, and the custom Picture model.

using Azure.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MVCLearn.Models;

This block defines a controller class named PictureController which inherits from Controller.

It contains a private field _context of type PictureContext to interact with the database.

The constructor injects an instance of PictureContext into the controller using dependency injection.

public class PictureController : Controller
{
    // Declare a private field to hold the PictureContext instance
    private readonly PictureContext _context;

    // Constructor to initialize the PictureContext instance using dependency injection
    public PictureController(PictureContext context)
    {
        _context = context;   
    }

The “Create” Action Method retrieves all pictures from the database asynchronously and passes them to the associated view.

It returns a view containing the list of pictures.

[HttpGet]
public async Task<IActionResult> Create()
{
    var pictures = await _context.Pictures.ToListAsync();
    return View(pictures);
}

The “GetImage” Action Method retrieves a specific image from the database based on its ID. If the image is found, it returns the image data with the appropriate content type. If the image is not found, it returns a 404 Not Found status code.

[HttpGet]
public async Task<IActionResult> GetImage(int id)
{
    var picture = await _context.Pictures.FindAsync(id);
    if (picture == null)
    {
        return NotFound();
    }
    return File(picture.PictureData, picture.PicContentType);
}

The “Remove” Action Method removes a specific image from the database based on its ID. If the image is found, it is removed from the database. It then redirects to the Create action to refresh the list of pictures.

[HttpGet]
public async Task<IActionResult> Remove(int id)
{
    var picture = await _context.Pictures.FindAsync(id);
    if (picture == null)
    {
        return NotFound();
    }
    _context.Pictures.Remove(picture);
    _context.SaveChanges();
    return RedirectToAction("Create");
}

The “UploadPictures” Action Method handles the upload of one or more pictures.

It receives a collection of uploaded files (IFormFileCollection) as a parameter.

For each uploaded file, it converts the file data to a byte array, creates a new Picture object, and adds it to the database.

After processing all files, it saves changes to the database and redirects to the Create action to refresh the list of pictures.

[HttpPost]
public async Task<IActionResult> UploadPictures(IFormFileCollection files)
{
    if (files != null && files.Count > 0)
    {
        foreach (var file in files.Where(f => f != null && f.Length > 0))
        {
            // Process each uploaded file
            // Convert file data to byte array
            // Create a new Picture object and add it to the database
        }
        // Save changes to the database
    }
    return RedirectToAction("Create");
}

Create The Upload Pictures View

Next, right click on the View method call in the “return View(pictures);” statement within the Create Action Method.

Follow the prompt to create a view named Create.cshtml.

The code in the view allows users to upload multiple pictures, displays them as thumbnails in a grid layout, and provides a modal dialog for viewing the selected image in a larger size when clicked. Additionally, it provides functionality to display the selected file names below the file input field and includes styling for the thumbnails and modal dialog.

@model IEnumerable<Picture>

@using (Html.BeginForm("UploadPictures", "Picture", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <!-- Input for selecting pictures -->
    <div>
        <label for="fileInput">Select Pictures:</label>
        <input type="file" name="files" id="fileInput" accept="image/*" multiple>
    </div>
    <!-- Button to upload pictures -->
    <button type="submit">Upload Pictures</button>
}

Begin the Create.cshtml code by including a model declaration indicating that the model for this view is an enumerable collection of Picture objects. The above code also includes a form for uploading pictures. It includes an input field of type file (<input type=”file”>) that allows users to select multiple images. The form is submitted to the UploadPictures action method of the Picture controller when the user clicks the “Upload Pictures” button.

<div id="modalImage" class="modal fade" tabindex="-1" role="dialog">
    <!-- Modal content for displaying image -->
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-body">
                <img id="imgModal" src="" class="img-responsive" style="max-width:100%;height:auto;">
            </div>
        </div>
    </div>
</div>

This part defines a modal dialog that will display the selected image in a larger size when clicked. It contains an empty img tag with the id imgModal where the selected image will be displayed.

<div class="row">
    <!-- Iterate over each picture in the model and display it as a thumbnail -->
    @foreach (var picture in Model)
    {
        <div class="col-md-4">
            <div class="thumbnail">
                <!-- Display the image thumbnail with a link to view it larger -->
                <img src="@Url.Action("GetImage", "Picture", new { id = picture.Id })" alt="@picture.PictureName" class="img-responsive" style="width:100px;height:100px;">
                <div class="caption">
                    <h6>@picture.PictureName</h6>
                    <!-- Link to remove the picture (not implemented in this code) -->
                    <a asp-action="Remove" asp-controller="Picture" asp-route-id="@picture.Id">Remove</a>
                </div>
            </div>
        </div>
    }
</div>

This section iterates over each Picture object in the model and displays it as a thumbnail in a grid layout. Each thumbnail image is wrapped in a div with the class thumbnail and contains the image itself along with its name. Additionally, each thumbnail is linked to the GetImage action method of the Picture controller, passing the picture’s ID as a parameter, allowing users to view the image larger.

@section scripts {
    <!-- JavaScript code for displaying the selected image in the modal -->
    <script>
        $(document).ready(function () {
            $('.thumbnail').click(function () {
                var imgSrc = $(this).find('img').attr('src');
                $('#imgModal').attr('src', imgSrc);
                $('#modalImage').modal('show');
            });
        });
        <!-- JavaScript code to display selected file names -->
        document.getElementById('fileInput').addEventListener('change', function () {
            var fileNames = [];
            for (var i = 0; i < this.files.length; i++) {
                fileNames.push(this.files[i].name);
            }
            document.getElementById('fileLabel').innerText = fileNames.join(', ');
        });
    </script>
}

This section contains JavaScript code that handles the functionality of displaying the selected image in the modal when clicked and displaying the selected file names in a label below the file input field.

Conclusion

Throughout this tutorial, we’ve covered the fundamentals of building a picture gallery with ASP.NET Core MVC. Here’s a summary of what we’ve learned:

  • We started by setting up the necessary dependencies and tools, including ASP.NET Core MVC and Entity Framework Core.
  • We created an Entity Framework model to represent pictures and students, enabling us to store and retrieve image data from the database.
  • In our MVC controller, we implemented actions to handle uploading, retrieving, and removing pictures, leveraging asynchronous programming for efficient handling of I/O operations.
  • Using Razor views, we built a user-friendly interface for displaying pictures, enabling users to browse and interact with the gallery seamlessly.

By following along with this tutorial, you’ve gained valuable insights into working with ASP.NET Core MVC, Entity Framework Core, and Razor views to develop a dynamic picture gallery application.

Please don’t hesitate to contact us via email to receive the access link to the full source code. Please include “Picture gallery” in the subject line.

By Admin

3 thoughts on “Implement Image Gallery with Asp.net Core MVC”
  1. Hey would you mind stating which blog platform you’re working with? I’m looking to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique. P.S Apologies for getting off-topic but I had to ask!

Leave a Reply

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