Bind Image src from Controller in ASP.NET Core MVC




This article is going to explain how to bind the img src tag from the Controller value in ASP.NET Core MVC. Let us see this with an example

The following is a screenshot of solution explorer. Here the image is stored in wwwroot-> images -> img.png


The below is a HomeController code.

IWebHostEnvironment is injected in the HomeController constructor to get the absolute path of the image. In the DisplayImage action, the ResponseCache attribute has been added to avoid the image caching.If it is cached, the browser will display the same cached image instead of the new requested image.In the response cache attribute, NoStore = true and Location = ResponseCacheLocation.None are added to avoid request and response cache storage

In the DisplayImage action code, the web root path is retrieved from _env.WebRootPath and combined with the image path. Finally it returns the file.

public class HomeController : Controller
{
    private readonly IWebHostEnvironment _env;
    public HomeController(IWebHostEnvironment env)
    {
        _env = env;
    }
    public IActionResult Index()
    {
        return View();
    }
    [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
    public IActionResult DisplayImage()
    {
        var webRoot = _env.WebRootPath;
        var file = System.IO.Path.Combine(webRoot, "\\images\\img.png");
        return File(file, "image/png");
    }
 }

The following is an Index.cshtml file. Here you can see the DisplayImage url is bound to the image tag src.

@{
    ViewData["Title"] = "Display Image";
    Layout = null;
}
<h4>Display Image from Controller</h4>
<img src="https://localhost:44378/Home/DisplayImage" alt="Image" />

Below is an output screenshot of the above. It shows the image.



In the browser developer tool, the DisplayImage action URL is assigned to the image src tags instead of the image path image.


I hope it will be helpful for you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example