Image Tag Helper in ASP.NET Core

Image Tag Helper in ASP.NET Core MVC Application

I will discuss the Image Tag Helper in ASP.NET Core MVC Web Application with Examples in this article. Please read our previous article, discussing the basics of Tag Helpers in ASP.NET Core MVC Application. As part of this article, we will discuss the following pointers. As part of this article, we will discuss the following pointers.

  1. Understanding the Browser Cache
  2. How to Disable Browser Cache?
  3. Why do we need an Image Tag Helper in ASP.NET Core?
  4. How Do We Use Image Tag Helper in ASP.NET Core?
  5. Understanding ASP.NET Core Image Tag Helper with an example
  6. How Does the Image Tag Helper Work in ASP.NET Core?
Understanding the Browser Cache:

When we visit a web page containing some images, most modern web browsers cache the images for future use. In the future, when we revisit the same web page, the browser loads the images from the cache instead of downloading the images from the server. This is not an issue in most cases, as the images are not often changed for a web page.

How to Disable Browser Cache?

You can also disable the browser cache. Once you disable the browser cache, the images will not be cached; instead, they will be downloaded from the server each time you visit the page. To disable the browser cache in Google Chrome, follow the steps below.

Press the F12 key to launch the Browser Developer Tools. Then click on the “Network” tab, and finally, check the “Disable Cache” checkbox as shown in the below image.

How to Disable Browser Cache

Why do we need an Image Tag Helper in ASP.NET Core?

If you disable the browser cache, it will download the image from the server each time. If you don’t disable the browser cache, it will serve the image from the browser cache. However, the problem with this approach is that if you change the image in the server, you will not get the updated image if the browser cache is not disabled.

To overcome the above problems, i.e., download the image from the server only when it has changed, or else serve the image from the browser cache, we need to use the Image Tag helper in the ASP.NET Core MVC Application.

The Image Tag Helper enhances the <img> tag to provide cache-busting behavior for static image files. A cache-busting string is a unique value representing the hash of the static image file appended to the asset’s URL. The unique string prompts clients to reload the image from the host web server, not the browser’s cache. If this is not clear at the moment, then don’t worry. We will understand this concept with an example.

What is an Image Tag Helper?

The Image Tag Helper in ASP.NET Core MVC simplifies the process of generating <img> elements for displaying images on your web pages. It helps ensure that image URLs are correctly generated, which is especially useful when dealing with dynamic content or different environments.

How Do We Use Image Tag Helper in ASP.NET Core MVC?

The primary usage of the Image Tag Helper is similar to the regular HTML <img> tag, but it allows you to specify the image source using the src attribute.

<img src="~/images/Image1.jpg" alt="My Image" />

Cache-Busting:
One of the benefits of the Image Tag Helper is that it can automatically append a cache-busting query string to the image URL. This ensures that browsers fetch the latest version of the image when it has been updated on the server.

<img src="~/images/Image1.jpg" alt="My Image" asp-append-version="true" />

The asp-append-version=”true” attribute will add a query string based on the image’s last modified timestamp, ensuring that the URL changes when the image changes.

Width and Height Attributes:
You can specify the image’s dimensions using the width and height attributes. This helps improve page loading performance by indicating the image dimensions to the browser before the image is fully loaded. 

<img src="~/images/Image1.jpg" alt="My Image" width="200" height="150" />

Additional Attributes:
The Image Tag Helper supports other attributes you might want to use with the <img> tag, such as class, style, alt, and more.

<img src="~/images/Image1.jpg" alt="My Image" class="img-thumbnail" style="border: 1px solid #ccc;" />

Using Model Binding:
You can also use the Image Tag Helper with model binding. If your view model has an image property, you can bind it directly to the src attribute. Assuming your view model has a property named ImageUrl:

<img asp-src="@Model.ImageUrl" alt="Image">

In this case, the asp-src attribute binds to your model’s ImageUrl property, generating the appropriate src attribute.

Understanding ASP.NET Core Image Tag Helper With an Example:

First, create a folder with the name images within the wwwroot folder of your application. Once you create the images folder, add images with the names Image1.jpg and Image2.jpg. For better understanding, add two different images, as shown in the below image.

Image1Image2

Once you add the above two images, your wwwroot folder should look as shown below.

Image Tag Helper in ASP.NET Core

Modifying Home Controller:

Next, modify the Home Controller as shown below. We have modified the HomeController to use the Index Action method, which returns a View.

using Microsoft.AspNetCore.Mvc;
namespace TagHelpersDemo.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
    }
}
Modifying Program Class:

Next, modify the Main method of the Program class to include static files middleware before the MVC middleware.

namespace TagHelpersDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            //Adding Static Files Middleware to Serve the Static Files
            //This Should be added before the MVC Middleware
            app.UseStaticFiles();

            //This should be included as want to use End Point Routing
            app.UseRouting();

            app.UseAuthorization();

            //Adding MVC Middleware to the Request processing Pipeline
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.Run();
        }
    }
}
Modifying _ViewImports.cshtml file:

Next, make sure to include the @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers inside the _ViewImports.cshtml file. So, modify the _ViewImports.cshtml file as follows.

@using TagHelpersDemo
@using TagHelpersDemo.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Modifying Index View:

Next, modify the Index View as shown below. Here, we have only the img tag, which loads the image Image1.jpg from the images folder. Along with the src attribute, where we set the path of the image, we have also used the asp-append-version attribute and set its value to true.

@{
    ViewBag.Title = "Index";
    Layout = null;
}

<img src="~/images/Image1.jpg" asp-append-version="true" />

With the above changes in place, run the application, and you should get the output as expected, as shown in the image below. Next, right-click on the page and then click on view the page source, as shown in the image below.

View Page Source

Once you view the page source code, you will find the following code for the image tag.

How Does the Image Tag Helper Work in ASP.NET Core

How Does the Image Tag Helper Work in ASP.NET Core?

The ASP.NET Core Image Tag Helper enhances the <img> tag to provide cache-busting behavior for static image files. That means based on the image’s content, a unique hash value is calculated and then appended to the image URL, as you can see in the above image. This unique hash value decides whether to load the image from the server or load the image from the browser cache. If the hash value changes, it will reload the image from the server; otherwise, it will reload the image from the cache.

Now, reload the page multiple times, and you will see the hash will not change; hence, it will load the image from the browser cache.

Now, rename Image1 as Image3 and Image2 as Image1 within your application’s images folder and reload the page. You will see a different hash value as well as the updated image, which proves that it loads the image from the server, as shown in the image below.

Image Tag Helper in ASP.NET Core MVC Application with Examples

When Should We Use Image Tag Helper in ASP.NET Core MVC?

The Image Tag Helper in ASP.NET Core MVC is useful in scenarios where you need to include images in your views and want to take advantage of its features to simplify image handling and improve performance. Here are situations when you should consider using the Image Tag Helper:

  • Dynamic Image URLs: When you need to display images with URLs that change dynamically based on data from your application or user input, the Image Tag Helper can automatically generate the correct URLs.
  • Including Images in Views: The primary purpose of the Image Tag Helper is to simplify the process of including images in your HTML views. If you have images that need to be displayed on your web pages, using the Image Tag Helper can make the markup cleaner and more readable.
  • Cache-Busting and Versioning: If your application frequently updates images, using the Image Tag Helper with the asp-append-version=”true” attribute helps ensure that browsers fetch the latest version. This is particularly important for preventing users from seeing outdated cached images.
  • Performance Optimization: You can improve page loading performance by specifying the width and height attributes in the Image Tag Helper. The browser can allocate space for the image before it’s fully loaded, reducing layout shifts and improving user experience.
  • Simplifying Markup: The Image Tag Helper simplifies the markup by handling the correct generation of the src attribute. This can be especially helpful when working with dynamic paths or URLs.
  • Model Binding: If your view model has an image property, you can bind it directly to the src attribute of the Image Tag Helper, making it easier to display images from your model.

In the next article, we will discuss the Environment Tag Helper in ASP.NET Core MVC Application. In this article, I explained the Image Tag Helper in the ASP.NET Core MVC Application with examples. I hope you enjoy this article.

1 thought on “Image Tag Helper in ASP.NET Core”

Leave a Reply

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