sunboy_sunboy
sunboy_sunboy

Reputation: 263

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

Upvotes: 0

Views: 701

Answers (1)

Rena
Rena

Reputation: 36645

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;

Upvotes: 1

Related Questions