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
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
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");
}
}
@{
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.
Comments
Post a Comment