Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show images from a folder using Razor MVC?

I am using Razor MVC and I would like to show images from "~/Content/uploads" folder. I came up with the following solution:

@foreach (FileInfo fileInfo in (new DirectoryInfo(Server.MapPath("~/Content/uploads"))
                                    .GetFiles().Where(x => x.Extension == ".jpg"))) {
    <img src="/@fileInfo
               .FullName
               .Substring(Server.MapPath("~/").Length)
               .Replace("\\", "/")"
         width="100">
}

The problem with the code is that I am taking the full file path and I am removing the Server.MapPath() prefix.

How can I simplify this code?

like image 303
Srđan Stipić Avatar asked Feb 09 '14 12:02

Srđan Stipić


1 Answers

You can use the UrlHelper class that is available on Razor pages.

@foreach (var imgPath in Directory.GetFiles(Server.MapPath("~/Content/uploads"), "*.jpg"))
{
    var img = new FileInfo(imgPath);
    <img src="@Url.Content(String.Format("~/Content/uploads/{0}", img.Name))" />
}
like image 71
Rowan Freeman Avatar answered Sep 22 '22 22:09

Rowan Freeman