Search code examples
htmlasp.netimageasp.net-corerazor-pages

Asp.Net Core 3.1 - Get Image from directory and display in razor view?


How can I take the image from the directory and display it?

"I saw similar posts but it did not help"

I did this but it didn't work

Controller :

     string[] filePaths = Directory.GetFiles(Path.Combine(_hostingEnv.WebRootPath, @"site\img\banner\"));          
       
        ViewBag.ListImgMainDefalt = filePaths;

View :

foreach (var item in ViewBag.ListImgMainDefalt)
                    {
                        <tr>                               

                            <td>
                                <img src="@item" />
                            </td>
                        </tr>

                    }

Resault : enter image description here


Solution

  • Change your code like below:

    string[] filePaths = Directory.GetFiles(Path.Combine(_hostingEnv.WebRootPath, @"site\img\banner\"));
    List<string> fileName = new List<string>();
    foreach (string filePath in filePaths)
    {
        fileName.Add(@"/site/img/banner/"+Path.GetFileName(filePath));
    }
    ViewBag.ListImgMainDefalt = fileName;