I have images in a folder and not in the database, i want to display the particular image (my image path is in the form of string) from controller to view, with other data in asp.net 6 mvc
I tried Viewbag, tempdata and all the other things. I am unable to find a way in .net 6, all the solutions are in previous version which is not working in .net 6
Things i have tried
view
//
controller
{
var data = _context.tbl_scotequine.Where(e => e.Ueln == ueln)
.Select(e => new EquineCard
{
name = e.Name1,
colour = e.Colour,
sex = e.Gender,
microchip = e.Microchip1
//Path = $"C:/Users/sonia/Downloads/scotequine original source code/storage/data/cards/uploads/cropped{ueln}.jpg"
});
var res = data.ToList()[0];
ViewBag.Path = Url.Content($"C:/Users/sonia/Downloads/scotequine original source code/storage/data/cards/uploads/cropped{ueln}.jpg");
return View(res);
}
I have also tried this
{
var Path = $"C:/Users/sonia/Downloads/scotequine original source code/storage/data/cards/uploads/cropped{ueln}.jpg";
var data = _context.tbl_scotequine.Where(e => e.Ueln == ueln)
.Select(e => new EquineCard
{
name = e.Name1,
colour = e.Colour,
sex = e.Gender,
microchip = e.Microchip1
image = Encoding.ASCII.GetBytes(Path)
});
var res = data.ToList()[0];
2
Answers
If to pass the local file location path to the view:
Then in the view use an additional method to obtain an image from the server side:
The controller side code:
Actually, if you have some file identifier like
Ueln
in your code, preferably to use it and pass to the view and then to theGetImage
method instead of manipulating with the full file path.In your controller action, you’re already retrieving the image path and setting it in the ViewBag. However, you should use Url.Content to generate a URL relative to the web application root
}
In your view (YourView.cshtml), you can display the image using the img tag with the URL from ViewBag.Path:
Make sure the image path provided in imagePath is relative to the wwwroot directory, which is where static files like images should be stored in an ASP.NET Core application. The Url.Content method generates a URL that is relative to the web application root.
Ensure that your application is configured to serve static files from the wwwroot folder in your Startup.cs
}