Back to: ASP.NET Core Tutorials For Beginners and Professionals
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.
- Understanding the Browser Cache
- How to Disable Browser Cache?
- Why do we need an Image Tag Helper in ASP.NET Core?
- How to use Image Tag Helper in ASP.NET Core?
- Understanding ASP.NET Core Image Tag Helper with an example
- 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?
If you want, you can also disable the browser cache. Once you disable the browser cache, it will not cache the images, and each and every time, it will download the images from the server when 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.
Why do we need an Image Tag Helper in ASP.NET Core?
If you disable the browser cache, then each and every time, it will download the image from the server. If you didn’t disable the browser cache, it will serve the image from the browser cache. But the problem with this approach is that if you change the image, then 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 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 to use Image Tag Helper in ASP.NET Core MVC?
Basic Usage:
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 the ImageUrl property of your model, 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.
Once you add the above two images, your wwwroot folder should look as shown below.
Modifying Home Controller:
Next, modify the Home Controller as shown below. We have modified the Home Controller to have only 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 as follows 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, now run the application, and you should get the output as expected, as shown in the below image. Next, right-click on the page and then click on the view the page source as shown in the below image.
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?
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 the images folder of your application and reload the page, and 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 below image.
The Image Tag Helper simplifies the inclusion of images in your views while providing helpful features like cache-busting and automatic URL generation. It’s essential to ensure that the src attribute points to the correct image path on your server. The cache-busting feature is particularly useful for ensuring that users see the latest version of images after updates.
When to use Image Tag Helper in ASP.NET Core MVC?
The Image Tag Helper in ASP.NET Core is specifically designed to simplify the process of generating <img> elements for displaying images on your web pages. It’s particularly useful when handling image URLs dynamically or ensuring proper URL generation based on different environments.
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.
- Responsive Images: When you need to display different image sizes for different device screen sizes (e.g., mobile vs. desktop), you can use the Image Tag Helper to generate the appropriate <img> elements with the correct srcset and sizes attributes.
- 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 of images. 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.
- Consistency: If you want to ensure a consistent approach to including images across your application, using the Image Tag Helper helps enforce this consistency. Developers will follow a standard syntax, making your codebase more uniform.
- 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.
- Avoiding Hardcoded Paths: When using the ~ symbol to refer to the root directory of your web application, the Image Tag Helper can automatically resolve the correct absolute path, avoiding issues with hardcoded relative paths that might break in different parts of your application.
- Non-Web Developers: If your development team includes designers or front-end developers who are more familiar with HTML than server-side programming, using the Image Tag Helper can make the code more approachable for them.
You should use the Image Tag Helper in ASP.NET Core whenever you need to display images on your web pages, especially in scenarios where you want to handle dynamic URLs, maintain image versioning, and ensure proper accessibility. The Image Tag Helper simplifies the process of generating correct and consistent <img> elements, helping you adhere to best practices for web development.
Note: Keep in mind that while the Image Tag Helper provides benefits, it might not be necessary in all situations. For simple static images that don’t require cache-busting or dynamic paths, using regular HTML <img> tags might be sufficient. Evaluate your requirements, including image updates, performance considerations, and your development team’s expertise, to determine whether the Image Tag Helper fits your application well.
In the next article, we will discuss the Environment Tag Helper in ASP.NET Core MVC Application. Here, in this article, I try to explain Image Tag Helper in ASP.NET Core MVC Application with Examples. I hope you enjoy this article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.
Thank u